Elasticsearch:仅返回突出显示的substring / keyword匹配项

时间:2018-03-22 12:25:56

标签: elasticsearch full-text-search elasticsearch-dsl

给定一个完整的字符串Knasweg 12, 9062 Knasweg, Österreich,如果我搜索这个确切的子字符串,如何只突出显示(并返回)子字符串Knasweg

换句话说,我想要这个查询:

GET _search
{
  "query": {
    "match": {
      "location.pretty_address": {
        "query": "Knasweg",
        "operator": "and",
        "fuzziness": 1
      }
    }
  },
  "highlight": {
    "pre_tags": "",
    "post_tags": "",
    "fields": {
      "location.pretty_address": {
        "highlight_query": {
          "bool": {
            "must": {
              "match": {
                "location.pretty_address": {
                  "query": "Knasweg"
                }
              }
            }
          }
        }
      }
    }
  }
}

返回

  "highlight": {
    "location.pretty_address": [
      "Knasweg"
    ]
  }

而不是

  "highlight": {
    "location.pretty_address": [
      "Knasweg 12, 9062 Knasweg, Österreich"
    ]
  }    

我的映射:

"location": {
  "dynamic": "true",
  "properties": {
    "pretty_address": {
      "type": "text",
      "fields": {
        "keyword": {
          "type": "keyword"
        }
      },
      "analyzer": "autocomplete_analyzer"
    }
}

我的设置:

"settings": {
  "index": {
    "analysis": {
      "analyzer": {
        "comma_analyzer": {
          "tokenizer": "comma_tokenizer"
        },
        "autocomplete_analyzer": {
          "filter": "lowercase",
          "tokenizer": "autocomplete_tokenizer"
        }
      },
      "tokenizer": {
        "autocomplete_tokenizer": {
          "type": "ngram",
          "min_gram": "3",
          "max_gram": "20"
        },
        "comma_tokenizer": {
          "pattern": ", ",
          "type": "pattern"
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

根据文档here-您应添加fragment_size参数并将其设置为1,其中1是查询中的令牌数:

GET _search
{
  "query": {
    "match": {
      "location.pretty_address": {
        "query": "Knasweg",
        "operator": "and",
        "fuzziness": 1
      }
    }
  },
  "highlight": {
    "pre_tags": "",
    "post_tags": "",
    "fragment_size" : 1,
    "fields": {
      "location.pretty_address": {
        "highlight_query": {
          "bool": {
            "must": {
              "match": {
                "location.pretty_address": {
                  "query": "Knasweg"
                }
              }
            }
          }
        }
      }
    }
  }
}