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