在Go语言中实现Elasticsearch的高亮功能,可以通过使用 github.com/olivere/elastic 这个库来完成。以下是一个简单的示例,展示了如何在查询时使用高亮:
package main
import (
"context"
"fmt"
"log"
"github.com/olivere/elastic/v7"
)
func main() {
// 创建客户端
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"), elastic.SetSniff(false))
if err != nil {
log.Fatalf("Error creating client: %s", err)
}
// 启用高亮
highlight := elastic.NewHighlight().
Fields(elastic.NewHighlighterField("content")).
PreTags("<em>").PostTags("</em>")
// 构建查询
query := elastic.NewBoolQuery().Must(elastic.NewMatchQuery("content", "关键字"))
// 执行搜索
searchResult, err := client.Search().
Index("your_index_name"). // 替换为你的索引名
Query(query).
Highlight(highlight).
Do(context.Background())
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
// 遍历结果
for _, hit := range searchResult.Hits.Hits {
var content string
if hit.Highlight != nil && len(hit.Highlight["content"]) > 0 {
content = hit.Highlight["content"][0]
} else {
content = "No highlight"
}
fmt.Printf("Document ID: %s\nContent: %s\n", hit.Id, content)
}
}
在这个示例中,我们首先创建了一个Elasticsearch客户端。然后,我们定义了一个高亮对象,指定了要高亮的字段和高亮标签。接着,我们构建了一个查询,使用了 MatchQuery 来搜索包含特定关键字的内容。在执行搜索时,我们通过 Highlight 方法添加了高亮设置。
搜索结果中,每个命中的文档都会有一个 Highlight 字段,其中包含了高亮后的字段值。如果没有找到高亮内容,可以设置一个默认值。
请注意,你需要将 "your_index_name" 替换为你的实际索引名,并且确保你的Elasticsearch服务正在运行且可以访问。
这个示例是基于 olivere/elastic 库的版本7,如果你使用的是其他版本的Elasticsearch或者对应的Go客户端库,可能需要进行相应的调整。更多详细信息和高级用法,可以参考官方文档或相关的教程。
func Test0004_EsQueryHilight(t *testing.T) { request.IndexName = "dev_contact_user" var highlight = elastic.NewHighlight().Fields(elastic.NewHighlighterField("short_name")). PreTags("<em>").PostTags("</em>") query := elastic.NewTermQuery("short_name", "古泳") // NewMatchAllQuery() var ctx = context.Background() res, err := request.EsClient.Client().Search().Index(request.IndexName).Query(query). Highlight(highlight).From(0).Size(2).Pretty(true).Do(ctx) if err != nil { golog.Error(err) } golog.Info(jsonutils.ToJsonPretty(res)) }
GET dev_biz_grouping_buy_line/_search/
{
"query": {
"match_phrase": {
"shop_name": "bobo商户"
}
},
"highlight": {
"fields":{
"shop_name":{"type":"plain"}
}
},
"size":1,
"sort": [
{
"shop_id": "desc"
},
{
"updated_by": "desc"
}
],
"aggs": {
"state": {
"stats": {
"field": "state"
}
},
"price": {
"stats": {
"field": "price"
}
}
}
}
{
"took" : 7,
"timed_out" : false,
"_shards" : {
"total" : 3,
"successful" : 3,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 53,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "dev_biz_grouping_buy_line_v1",
"_type" : "_doc",
"_id" : "967155469545537539",
"_score" : null,
"_source" : {
"id" : 967155469545537539,
"created_at" : 1715222826002700000,
"updated_at" : 1715222872140472000,
"created_by" : 722827384120016897,
"updated_by" : 722827384120016897,
"shop_id" : 722827384433508353,
"shop_name" : "bobo商户",
"shop_member_id" : 722827384720097281,
"shop_member_name" : "bobo",
"group_buying_id" : 967155469273890819,
"published_line_id" : 931257805143212035,
"line_id" : 1683398832928333824,
"line_type" : "purchase_order_line",
"part_number" : "AW2P-D",
"part_brand" : "Amphenol",
"date_code" : "2021年",
"lead_time" : "12-14周",
"packing" : "",
"mpq" : 1,
"published_line_number" : "B000000123405",
"list_order" : 0,
"qty" : 1,
"currency_id" : 8,
"currency" : "CNY",
"currency_symbol" : "¥",
"price" : 99999,
"moq" : 2,
"state" : 10,
"ordered_qty" : 0,
"paid_qty" : 0,
"published_flag" : "N"
},
"highlight" : {
"shop_name" : [
"<em>b</em><em>o</em><em>b</em><em>o</em><em>商</em><em>户</em>"
]
},
"sort" : [
"722827384433508353",
"722827384120016897"
]
}
]
},
"aggregations" : {
"price" : {
"count" : 53,
"min" : 0.0,
"max" : 1000000.0,
"avg" : 298698.1320754717,
"sum" : 1.5831001E7
},
"state" : {
"count" : 53,
"min" : 10.0,
"max" : 40.0,
"avg" : 29.245283018867923,
"sum" : 1550.0
}
}
}