Bootstrap

go-elasticsearch创建ik索引并进行查询操作

es-go client引入gomod

go get github.com/elastic/go-elasticsearch/v8@latest

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

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

创建索引

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())
}

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

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"])
}

插入或者更新数据并查询

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

;