首页 > 解决方案 > 无法在 Elasticsearch 中突出显示动态模板字段值

问题描述

跟进这个问题

我有一个动态模板,它将 JSON blob 的文本复制到单个文本字段,我想在该字段上搜索并突出显示匹配项。这是我的 ES 6.5 的完整代码

DELETE /test
PUT /test?include_type_name=true
{
  "settings": {"number_of_shards": 1,"number_of_replicas": 1},
  "mappings": {
    "_doc": {
      "dynamic_templates": [
        {
          "full_name": {
            "match_mapping_type": "string",
            "path_match": "content.*",
            "mapping": {
              "type": "text",
              "copy_to": "content_text"
            }
          }
        }
      ],
      "properties": {
        "content_text": {
          "type": "text"
        },
        "content": {
          "type": "object",
          "enabled": "true"
        }
      }
    }
  }
}

PUT /test/_doc/1?refresh=true
{
  "content": {
    "a": {
      "b": {
        "text": "42"
      }
    }
  }
}

GET /test/_search
{
  "query": {
    "match": {
      "content_text": "42"
    }
  },
  "highlight": {
    "fields": {
      "content_text": {}
    }
  }
}

响应未显示突出显示的content_text

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.2876821,
        "_source" : {
          "content" : {
            "a" : {
              "b" : {
                "text" : "42"
              }
            }
          }
        }
      }
    ]
  }
}

如您所见,该content_text字段未突出显示。它也根本不在响应中。如何获得该字段的亮点以显示?

标签: elasticsearch

解决方案


这是一个棘手的问题,但是一旦您阅读了以下内容,就会变得有意义。

根据有关 highlighting 的官方文档,字段的实际内容必须存在于某处。因此,如果未存储该字段(即映射未设置store为 true),_source则加载实际字段并从中提取相关字段_source

在您的情况下,该content_text字段在文档中不存在_source(即它只是从 中存在的其他文本字段索引content.*)并且在映射中,该store参数未设置为 true (默认情况下为 false)。

因此,您只需将映射更改为:

    "content_text": {
      "store": true,
      "type": "text"
    },

然后您的查询将产生以下结果:

    "highlight" : {
      "content_text" : [
        "<em>42</em>"
      ]
    }

推荐阅读