Elasticsearch使用multi_match突出显示

时间:2017-05-16 07:57:16

标签: elasticsearch

我使用带有简单匹配查询的ES突出显示:

GET /_search
{
   "query": {
      "match": {
         "Text": "key words here"
      }
   },
   "highlight": {
      "pre_tags" : ["<span class='highlighter'>"],
      "post_tags" : ["</span>"],
      "fields": {
         "Text": {
            "fragment_size": 400,
            "number_of_fragments": 1,
            "no_match_size" : 20
         }
      }
   }
}

这很好用,并且突出显示Text在结果中返回指定的标记。

我想在multi_match查询上使用突出显示,如下所示:

GET /_search
{
   "query": {
      "multi_match": {
         "query": "GB RAM",
         "operator": "AND",
         "fields": "_all"
      }
   },
   "highlight": {
         "pre_tags": [
            "<span class='highlighter'>"
         ],
         "post_tags": [
            "</span>"
         ],
         "fields": {
            "Text": {
               "fragment_size": 400,
               "number_of_fragments": 1,
               "no_match_size": 20
            }
         }
      }
}

这不是很有效,返回的高亮文本是20个字符长(no_match_size),如下所示:

 "highlight": {
    "Text": ["        DVD-RAM"]
  }

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

You will have to modify the mappings first to enable store:true in the mappings. Since highlight need exact string value for it to work as _all field doesn't include itself in source.

Change mappings to set store:true for _all

PUT highlight_index_2

{
  "mappings": {
    "type_1" : {
     "_all": {
        "enabled": true,
        "store": true
      }
    }
  }
}

Next you will need to tweak your query a bit. You are getting highlights for only Text fields as your query specify the lucene highlighter to highlight only for Text field. You can modify you query like follows

{
    "query": {
        "query_string": {
            "fields": [
                "_all"
            ],
            "query": "this is the"
        }
    },
    "highlight": {
        "pre_tags": [
            "<span class='highlighter'>"
        ],
        "post_tags": [
            "</span>"
        ],
        "fields": {
            "_all": {
                "fragment_size": 400,
                "number_of_fragments": 2,
                "no_match_size": 20
            }
        }
    }
}

Make sure to tune number of fragments for highlighting multiple fields.

答案 1 :(得分:1)

感谢user3775217的回答。这是最终为我工作的查询

GET /_search
{
   "_source": {
        "exclude": [ "Text" ]
   },
   "query": {
        "multi_match": {
            "query": "DICTIONARY",
            "operator": "AND",
            "fields": "_all"
        }
    },
   "highlight": {
      "pre_tags": [
         "<span class='highlighter'>"
      ],
      "post_tags": [
         "</span>"
      ],
      "fields": {
         "Text": {
            "require_field_match": false,
            "fragment_size": 400,
            "number_of_fragments": 1,
            "no_match_size": 20
         }
      }
   },
   "size": 100
}

http://kempe.net/blog/2015/02/25/elasticsearch-query-full-text-search.html