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

相关推荐
P7进阶路8 分钟前
Spring Boot应用关闭分析
java·spring boot·后端
计算机-秋大田33 分钟前
基于微信小程序的消防隐患在线举报系统设计与实现(LW+源码+讲解)
java·spring boot·后端·微信小程序·小程序·课程设计
极客先躯1 小时前
高级java每日一道面试题-2025年01月27日-框架篇[SpringBoot篇]-如何在Spring Boot启动的时候运行一些特定的代码?
java·spring boot·后端·初始化·启动执行
m0_748235951 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
m0_674031431 小时前
Spring boot启动原理及相关组件
数据库·spring boot·后端
码界筑梦坊2 小时前
基于Flask的全国星巴克门店可视化分析系统的设计与实现
后端·python·flask·毕业设计
csucoderlee2 小时前
go语言中的Stringer的使用
开发语言·后端·golang
苏-言2 小时前
Spring Boot Web项目全解析:从前端请求到后端处理
前端·spring boot·后端
雨会停rain2 小时前
tomcat如何配置保存7天滚动日志
java·后端·tomcat
雪芽蓝域zzs3 小时前
SpringBoot开发(五)SpringBoot接收请求参数
spring boot·后端·lua