Elasticsearch - 文档中片段的位置

Jac*_*kel 5 elasticsearch

我正在执行如下所示的短语查询。它返回给我按相关性排序的突出显示的片段。当然,我希望用户单击某个片段,然后我会将文档滚动到相应的位置。但是,我在 Elasticsearch 中看不到任何方法来找出片段在原始文档中的位置。有任何想法吗?

GET documents/doc/_search
{
   "query": {
        "match_phrase": {
            "text": {
                "query": "hello world",
                "slop":  10
            }
        }
    }, 
    "highlight" : {
        "order" : "score",
        "fields" : {
            "text" : {"fragment_size" : 100, "number_of_fragments" : 10}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*kel 3

与此同时,我们找不到合适的解决方案,最终得到了以下 hack(对我们来说非常有效):在索引之前,我们用“[index]”注释文本中的每个单词,以便“一些要索引的文本”变为“ some[00] text[01] to[02] index[03] ”。然后我们使用 char 过滤器,如下所示。当返回突出显示时,我们从突出显示文本中解析出单词位置。

"settings": {
    "analysis": {
      "char_filter": {
        "remove_annotation": {
          "type": "pattern_replace",
          "pattern": "\\[[0-9]+\\]",
          "replacement": ""
        }
      },
      "analyzer": {
        "annotated_english_language_analyzer": {
          "type": "custom",
          "char_filter": [
            "remove_annotation"
          ],
          ...
Run Code Online (Sandbox Code Playgroud)

请注意,注释索引应填充为log10(text_length)+1数字,以便找到的突出显示的宽度(注释删除后)不会取决于找到它的位置(文本的开头与结尾)。