如何使用 golang bleve 搜索结果?

use*_*108 4 full-text-search go bleve

我是 Go and Bleve 的新手(对不起,如果我问的是琐碎的事情......)。这个搜索引擎似乎非常好,但是在处理搜索结果时我陷入了困境。

假设我们有一个结构:

type Person struct {
    Name string `json:"name"`
    Bio  string `json:"bio"`
}
Run Code Online (Sandbox Code Playgroud)

现在,我们从数据库中提取数据(使用 sqlx lib):

rows := []Person{}
db.Select(&rows, "SELECT * FROM person")
Run Code Online (Sandbox Code Playgroud)

...并将其编入索引:

index.Index, err = bleve.Open("index.bleve")

batch := index.Index.NewBatch()

i := 0
for _, row := range rows {
    rowId := fmt.Sprintf("%T_%d", row, row.ID)
    batch.Index(rowId, row)

    i++
    if i > 100 {
        index.Index.Batch(batch)
        i = 0
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我们已经创建了索引。它工作得很好。

使用bleve 命令行实用程序,它可以正确返回数据:

bleve query index.bleve doe

3 matches, showing 1 through 3, took 27.767838ms
    1. Person_68402 (0.252219)
    Name
        Doe
    Bio
        My name is John Doe!

    2. ...
Run Code Online (Sandbox Code Playgroud)

在这里我们看到 bleve 有存储NameBio字段。

现在我想通过我的代码访问它!

query := bleve.NewMatchAllQuery()
searchRequest := bleve.NewSearchRequest(query)
searchResults, _ := index.Index.Search(searchRequest)

fmt.Println(searchResults[0].ID) // <- This works
Run Code Online (Sandbox Code Playgroud)

但我不仅想要 ID,然后查询数据库以获取剩余的日期。为避免命中 database,我希望能够执行以下操作:

fmt.Println(searchResults[0].Bio) // <- This doesn't work :(
Run Code Online (Sandbox Code Playgroud)

能否请你帮忙?

Mos*_*vah 8

搜索结果中的每个匹配项都是DocumentMatch。您可以在文档中看到DocumentMatchFields这是一个map[string]interface{}和可以如下访问:

searchResults.Hits[0].Fields["Bio"].(string)
Run Code Online (Sandbox Code Playgroud)

默认情况下,Bleve 不会在结果中包含文档的字段。您必须提供要返回的字段列表SearchRequest.Fields( 的参数index.Search)。或者,您可以设置

searchRequest.Fields = []string{"*"}
Run Code Online (Sandbox Code Playgroud)

返回所有字段。