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接口的效率好上许多。

相关推荐
小白男神3 分钟前
MySQL进阶学习三(视图)
后端·mysql
猿人谷4 分钟前
Jev:当 AI 不再生成 Token,而是直接做决策
后端·langchain·aigc
苍何5 分钟前
WorkBuddy + 腾讯乐享,原来知识库还能这么用
后端
站大爷IP8 分钟前
Python的生成器把我坑惨了,原来yield和return的区别这么大
后端
苍何9 分钟前
一份来自大厂内部的《AI 原生实践避坑指南》
后端
codigger32 分钟前
服务器又卡了?一篇讲透 Linux 性能排查(基础四件套 + perf/strace/火焰图)
linux·后端·性能优化
+VX:Fegn089543 分钟前
计算机毕业设计|基于java+ vue共享单车信息系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
苏渡苇1 小时前
Spring Insight 里如何把 Span 画成瀑布时间线
后端·spring·spring cloud·springboot·监控·apm
Charlie_Byte1 小时前
Spring AI 2 手把手:把 filesystem MCP Server 跑通(SSE / stdio + 真调工具)
后端
程序猿DD1 小时前
OctaFuse Gateway 2.11.0:流式请求优化、用户折扣策略与错误契约升级
前端·后端