在Elasticsearch中为多值字段突出显示整个内容

16

利用 Elasticsearch 的高亮显示功能:

"highlight": {
  "fields": {
    "tags": { "number_of_fragments": 0 }
  }
}

如果设置number_of_fragments: 0,则不会生成任何片段,但是将返回字段的整个内容。对于短文本很有用,因为文档可以像平常一样显示,人们也可以轻松地扫描高亮部分。

如果一个文档包含多个值的数组,该如何使用?

PUT /test/doc/1
{
  "tags": [
    "one hit tag",
    "two foo tag",
    "three hit tag",
    "four foo tag"
  ]
}

GET /test/doc/_search
{
  "query": { 
    "match": { "tags": "hit"} 
  }, 
  "highlight": {
    "fields": {
      "tags": { "number_of_fragments": 0 }
    }
  }
}

现在我想要向用户展示:

1个结果:

文档1,标记为:

"一个命中标记","两个foo标记","三个命中标记","四个foo标记"

不幸的是,这是查询的结果:

{
     "took": 1,
     "timed_out": false,
     "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
     },
     "hits": {
        "total": 1,
        "max_score": 0.10848885,
        "hits": [
           {
              "_index": "test",
              "_type": "doc",
              "_id": "1",
              "_score": 0.10848885,
              "_source": {
                 "tags": [
                    "one hit tag",
                    "two foo tag",
                    "three hit tag",
                    "four foo tag"
                 ]
              },
              "highlight": {
                 "tags": [
                    "one <em>hit</em> tag",
                    "three <em>hit</em> tag"
                 ]
              }
           }
        ]
     }
  }

我该如何使用这个来到达:

   "tags": [
      "one <em>hit</em> tag",
      "two foo tag",
      "three <em>hit</em> tag",
      "four foo tag"
   ]

1
还没有任何进展吗?你是如何解决这个问题的?我也遇到了同样的问题。 - vmeln
根据这个问题,这个功能仍然缺失... - alex kucksdorf
使用 'fragmenter' : 'simple' - tjvg1991
1个回答

2

一个可能的方法是从高亮字段中删除<em> html标签。然后在原始字段中查找它们:

tags = [
   "one hit tag",
   "two foo tag",
   "three hit tag",
   "four foo tag"
]
highlighted = [
  "one <em>hit</em> tag",
  "three <em>hit</em> tag",
] 

highlighted.each do |highlighted_tag|
  if (index = tags.index(highlighted_tag.gsub(/<\/?em>/, '')))
    tags[index] = highlighted_tag
  end
end

puts tags #=> 
# one <em>hit</em> tag
# two foo tag
# three <em>hit</em> tag
# four foo tag

这段代码并不会获得最佳代码的奖项,但我认为它能够完成任务。

2
不包括多值字段“标签”中相同值出现两次的情况。 - mlangenberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接