es官方go客户端创建ik索引并进行查询操作

es-go client引入gomod

go 复制代码
go get github.com/elastic/go-elasticsearch/v8@latest

连接es服务器(不经过安全校验)

go 复制代码
cfg := elasticsearch.Config{
    Addresses: []string{
       "http://localhost:9200",
    },
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
    panic(err)
}

创建索引

go 复制代码
func createIndex(es *elasticsearch.Client) {
    // 创建索引的 JSON 配置
    indexName := "my_index"
    indexMapping := map[string]interface{}{
       "settings": map[string]interface{}{
          "analysis": map[string]interface{}{
             "analyzer": map[string]interface{}{
                "ik_analyzer": map[string]interface{}{
                   "type":      "custom",
                   "tokenizer": "ik_max_word",
                },
             },
          },
       },
       "mappings": map[string]interface{}{
          "properties": map[string]interface{}{
             "title": map[string]interface{}{
                "type":     "text",
                "analyzer": "ik_analyzer",
             },
             "content": map[string]interface{}{
                "type":     "text",
                "analyzer": "ik_analyzer",
             },
          },
       },
    }
    // 将索引配置转换为 JSON 字符串
    indexMappingJSON, err := json.Marshal(indexMapping)
    if err != nil {
       log.Fatalf("Error marshaling the index mapping: %s", err)
    }

    // 创建索引请求
    req := esapi.IndicesCreateRequest{
       Index: indexName,
       Body:  strings.NewReader(string(indexMappingJSON)),
    }

    // 发送请求
    res, err := req.Do(context.Background(), es)
    if err != nil {
       log.Fatalf("Error creating the index: %s", err)
    }
    defer res.Body.Close()

    // 检查响应
    if res.IsError() {
       log.Fatalf("Error creating the index: %s", res.String())
    }

    fmt.Printf("Index created: %s\n", res.String())
}

校验索引分词效果是否生效

go 复制代码
func use_analyze(es *elasticsearch.Client) {
    // 分词测试的 JSON 配置
    analyzeRequest := map[string]interface{}{
       "text":     "今天天气真好,适合出去玩",
       "analyzer": "ik_analyzer",
    }

    // 将分词请求转换为 JSON 字符串
    analyzeRequestJSON, err := json.Marshal(analyzeRequest)
    if err != nil {
       log.Fatalf("Error marshaling the analyze request: %s", err)
    }

    // 创建分词请求
    req := esapi.IndicesAnalyzeRequest{
       Index: "my_index",
       Body:  strings.NewReader(string(analyzeRequestJSON)),
    }

    // 发送请求
    res, err := req.Do(context.Background(), es)
    if err != nil {
       log.Fatalf("Error analyzing the text: %s", err)
    }
    defer res.Body.Close()
    // 检查响应
    if res.IsError() {
       log.Fatalf("Error analyzing the text: %s", res.String())
    }

    // 解析响应
    var result map[string]interface{}
    if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
       log.Fatalf("Error parsing the response: %s", err)
    }

    // 输出分词结果
    fmt.Printf("Tokens: %+v\n", result["tokens"])
}

插入或者更新数据并查询

go 复制代码
func insertAndSearch(es *elasticsearch.Client) {
    // 插入文档
    doc := map[string]interface{}{
       "title":   "测试文档",
       "content": "今天天气真好,适合出去玩",
    }

    docJSON, err := json.Marshal(doc)
    if err != nil {
       log.Fatalf("Error marshaling the document: %s", err)
    }

    req := esapi.IndexRequest{
       Index:      "my_index",
       DocumentID: "1",
       Body:       strings.NewReader(string(docJSON)),
    }

    res, err := req.Do(context.Background(), es)
    if err != nil {
       log.Fatalf("Error indexing the document: %s", err)
    }
    defer res.Body.Close()
    if res.IsError() {
       log.Fatalf("Error indexing the document: %s", res.String())
    }

    fmt.Printf("Document indexed: %s\n", res.String())

    // 查询文档
    query := map[string]interface{}{
       "query": map[string]interface{}{
          "match": map[string]interface{}{
             "content": "天气",
          },
       },
    }

    queryJSON, err := json.Marshal(query)
    if err != nil {
       log.Fatalf("Error marshaling the query: %s", err)
    }

    searchReq := esapi.SearchRequest{
       Index: []string{"my_index"},
       Body:  strings.NewReader(string(queryJSON)),
    }
    searchRes, err := searchReq.Do(context.Background(), es)
    if err != nil {
       log.Fatalf("Error searching the document: %s", err)
    }
    defer searchRes.Body.Close()

    if searchRes.IsError() {
       log.Fatalf("Error searching the document: %s", searchRes.String())
    }

    var searchResult map[string]interface{}
    if err := json.NewDecoder(searchRes.Body).Decode(&searchResult); err != nil {
       log.Fatalf("Error parsing the search response: %s", err)
    }

    fmt.Printf("Search results: %+v\n", searchResult)
    println("search res:", searchRes.String())
}

综上就完成了es go客户端操作es服务器的相关操作

总结

本次测试用例是在kimi智能助手的帮助下写的,合理使用人工智能确实能够极大程度的提高效率,比单纯的阅读、一个个查询文档、api接口的效率好上许多。

相关推荐
麦兜*17 分钟前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
大只鹅40 分钟前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
ai小鬼头43 分钟前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
IT_10241 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
bobz9652 小时前
动态规划
后端
stark张宇2 小时前
VMware 虚拟机装 Linux Centos 7.9 保姆级教程(附资源包)
linux·后端
亚力山大抵3 小时前
实验六-使用PyMySQL数据存储的Flask登录系统-实验七-集成Flask-SocketIO的实时通信系统
后端·python·flask
超级小忍3 小时前
Spring Boot 中常用的工具类库及其使用示例(完整版)
spring boot·后端
CHENWENFEIc3 小时前
SpringBoot论坛系统安全测试实战报告
spring boot·后端·程序人生·spring·系统安全·安全测试
重庆小透明4 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存