1. Client接口相关
- Elasticsearch客户端接口: elasticsearch.Client 是Elasticsearch操作的主要入口接口。它提供了许多方法用于与Elasticsearch集群进行交互。
- 例如, Index 方法用于向Elasticsearch索引文档。示例代码可能如下:
go 复制
client, err := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
})
doc := map[string]interface{}{
"title": "My Document",
"content": "This is the content of my document",
}
res, err := client.Index("my_index", doc)
- 这里 client.Index 就是通过 elasticsearch.Client 接口调用索引文档的操作。
2. Search接口相关
- SearchRequest和SearchResponse接口:用于执行搜索操作。 SearchRequest 用于构建搜索请求,你可以设置查询条件、过滤条件、排序等信息。 SearchResponse 则是搜索操作返回的结果接口。
- 例如:
go 复制
searchResult, err := client.Search(
client.Search.WithIndex("my_index"),
client.Search.WithQuery(elastic.NewMatchAllQuery()),
)
if err!= nil {
panic(err)
}
- 这里 client.Search 方法接受 SearchRequest 相关的配置(如 WithIndex 和 WithQuery )构建搜索请求,返回的结果是 SearchResponse 类型,可以进一步处理搜索结果中的文档等信息。
3. Index管理接口
- Indices接口相关操作:用于管理Elasticsearch中的索引。例如创建索引、删除索引、获取索引信息等操作。
- 像 client.Indices.Create 用于创建索引:
go 复制
createIndex, err := client.Indices.Create("new_index")
if err!= nil {
panic(err)
}
- 这里通过 client.Indices 这个与索引管理相关的接口来操作索引的创建。
4. Document操作接口
- Get接口:用于根据文档ID获取单个文档。例如:
go 复制
getResult, err := client.Get("my_index", "document_id")
if err!= nil {
panic(err)
}
- 这里 client.Get 是获取文档的操作接口,通过索引名和文档ID来获取特定的文档。
5. Bulk操作接口
- Bulk接口:用于批量操作文档,如批量插入、更新或删除文档。可以通过构建 BulkRequest 并使用 client.Bulk 方法来执行批量操作。例如:
go 复制
bulkRequest := client.Bulk()
// 添加批量操作的文档
doc1 := elastic.NewBulkIndexRequest().Index("my_index").Doc(map[string]interface{}{
"title": "Doc1",
"content": "Content of doc1",
})
bulkRequest = bulkRequest.Add(doc1)
// 执行批量操作
bulkResponse, err := client.Bulk(bulkRequest)
if err!= nil {
panic(err)
}
1. WithIndex 接口
- 在Go语言中使用Elasticsearch v7时, WithIndex 是用于在搜索请求( SearchRequest )中指定要搜索的索引的一种方式。
- 示例:
go 复制
client, err := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
})
searchResult, err := client.Search(
client.Search.WithIndex("your_index_name"),
// 可以添加其他搜索配置
)
if err!= nil {
panic(err)
}
- 这里 client.Search.WithIndex("your_index_name") 将搜索请求的目标索引设置为 your_index_name 。如果要搜索多个索引,可以传入多个索引名,例如 client.Search.WithIndex("index1", "index2") 。
2. WithQuery 接口
- WithQuery 用于在搜索请求中设置查询条件。它接受一个查询对象,例如 elastic.NewMatchAllQuery() 用于创建一个匹配所有文档的查询,或者 elastic.NewTermQuery("field_name", "term_value") 用于创建一个基于词条的查询。
- 示例:
go 复制
matchQuery := elastic.NewMatchQuery("title", "search_term")
searchResult, err := client.Search(
client.Search.WithIndex("your_index_name"),
client.Search.WithQuery(matchQuery),
// 可以添加其他搜索配置
)
if err!= nil {
panic(err)
}
- 在这个例子中, client.Search.WithQuery(matchQuery) 将搜索请求的查询条件设置为一个匹配 title 字段中包含 search_term 的文档的查询。通过这种方式,可以构建各种复杂的查询,如布尔查询、范围查询等,只需要构建相应的查询对象并使用 WithQuery 接口将其添加到搜索请求中。