【问题标题】:Highlight whole content in Elasticsearch for multivalue fields在 Elasticsearch 中突出显示多值字段的全部内容
【发布时间】:2014-10-23 07:18:12
【问题描述】:

使用 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"
   ]

【问题讨论】:

  • 这个还是什么都没有?你是如何解决这个问题的?我有同样的问题。
  • 根据this issue这个功能仍然缺失...
  • 使用'fragmenter' : 'simple'

标签: elasticsearch highlighting


【解决方案1】:

一种可能性是从突出显示的字段中去除&lt;em&gt; html-tags。然后在原始字段中查找它们:

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

这并没有为最漂亮的代码付出代价,但我认为它可以完成工作。

【讨论】:

  • 不会隐藏多值字段'tags'中相同值出现两次的情况。
猜你喜欢
  • 2013-05-22
  • 2013-08-24
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2015-03-30
  • 2015-11-06
  • 2014-11-23
  • 2020-04-27
相关资源
最近更新 更多