使用 Unstructured.io 和 Elasticsearch 向量数据库搜索复杂文档
package main
import (
"context"
"fmt"
"log"
"github.com/olivere/elastic"
)
// 初始化Elasticsearch客户端
func NewElasticClient(addr string) (*elastic.Client, error) {
client, err := elastic.NewClient(elastic.SetURL(addr))
if err != nil {
return nil, err
}
info, code, err := client.Ping(addr).Do(context.Background())
if err != nil {
return nil, err
}
fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
return client, nil
}
// 使用Elasticsearch客户端执行搜索查询
func SearchWithElastic(client *elastic.Client, index string) {
// 构建查询
query := elastic.NewFunctionScoreQuery().
Query(elastic.NewMatchQuery("content", "interesting")).
Function(
elastic.NewWeightFunction().
Filter(elastic.NewMatchQuery("status", "published")).
Weight(100),
)
// 执行搜索
searchResult, err := client.Search().
Index(index).
Query(query).
Sort("_id", true).
From(0).Size(10).
Do(context.Background())
if err != nil {
log.Fatal(err)
}
// 分析搜索结果
if searchResult.Hits.TotalHits > 0 {
fmt.Printf("Found a total of %d documents\n", searchResult.Hits.TotalHits)
for _, hit := range searchResult.Hits.Hits {
fmt.Printf("Found document ID: %s\n", hit.Id)
}
} else {
fmt.Print("Found no documents\n")
}
}
func main() {
client, err := NewElasticClient("http://localhost:9200")
if err != nil {
log.Fatalf("Error creating Elasticsearch client: %v", err)
}
SearchWithElastic(client, "vector_search_index")
}
这段代码首先导入了必要的包,并定义了初始化Elasticsearch客户端和使用该客户端执行搜索查询的函数。在main
函数中,它创建了一个Elasticsearch客户端,并调用了执行搜索的函数。这个例子展示了如何使用Elasticsearch的Go语言客户端来执行复杂的搜索查询。
评论已关闭