与ElasticSearch完全匹配(在查询时)

Mic*_*unk 7 java elasticsearch

我有一个位置索引,它有很多位置名称及其各自的国家/地区.

然后我想知道我们在国家代码为"DE"的国家/地区是否有标题为"Berlin"的地点.

这是我的Java代码尝试:

SearchResponse response = client.prepareSearch("locations")
                .setQuery(QueryBuilders.matchQuery("title", "Berlin"))
                .setFilter(FilterBuilders.termFilter("country", "DE"))
                .execute()
                .actionGet();
Run Code Online (Sandbox Code Playgroud)

但这给了我太多的答复,例如"柏林动物园"的结果等等.我需要完全匹配.

(但请注意,我还有其他需要此子字符串/文本搜索匹配的方案.)

有没有办法决定查询时间,而不是在索引时间指望哪个行为(精确与分析文本)?

Sco*_*ice 10

将您执行术语过滤的字段编入索引为not_analyzed.例如,您可以将"country"字段索引为multi_field,其中一个子字段为not_analyzed:

        "country": {
            "type": "multi_field",
            "fields": {
                "country": {"type": "string", "index": "analyzed"},
                "exact": {"type": "string","index": "not_analyzed"}
            }
        }
Run Code Online (Sandbox Code Playgroud)

此外,您可以对"标题"字段执行相同操作以执行术语查询:

        "title": {
            "type": "multi_field",
            "fields": {
                "title": {"type": "string", "index": "analyzed"},
                "exact": {"type": "string","index": "not_analyzed"}
            }
        }
Run Code Online (Sandbox Code Playgroud)

然后在查询时,如果您希望标题的确切术语"柏林"按照确切的术语"DE"进行过滤,请使用带有not_analyzed字段的术语查询和术语过滤器:

SearchResponse response = client.prepareSearch("locations")
                .setQuery(QueryBuilders.termQuery("title.exact", "Berlin"))
                .setFilter(FilterBuilders.termFilter("country.exact", "DE"))
                .execute()
                .actionGet();
Run Code Online (Sandbox Code Playgroud)

请注意,术语过滤器和术语查询需要not_analyzed字段才能工作(即返回完全匹配).

  • 有没有办法在查询时执行not_analyzed查询,而不更改映射? (2认同)