ElasticSearch+Spring:如何给所有person索引查询追加状态过滤模板
无需修改原有查询,为Elasticsearch person索引全局追加active状态过滤条件
问题背景
我们有一个包含status字段的person索引,现有6个逻辑、参数各不相同的查询语句用于检索文档。需求变更后,所有针对该索引的查询仅需返回active状态的文档,希望找到不用逐个修改原有查询的解决方案,需追加的过滤逻辑如下:
{ "bool": { "should": [ { "nested": { "path": "additionalAttributes", "query": { "terms": { "additionalAttributes.status": [ "active" ] } } } }, { "bool": { "must_not": [ { "nested": { "path": "additionalAttributes", "query": { "exists": { "field": "additionalAttributes.status" } } } } ] } } ] }
解决方案1:带过滤条件的索引别名(推荐)
这是最省心的方案,无需修改原有查询的任何内容,只需给person索引创建一个附带过滤规则的别名,后续所有查询直接指向该别名即可:
- 创建带过滤的索引别名
执行以下API请求,创建名为person_active的别名,自动绑定指定的过滤逻辑:
POST /_aliases { "actions": [ { "add": { "index": "person", "alias": "person_active", "filter": { "bool": { "should": [ { "nested": { "path": "additionalAttributes", "query": { "terms": { "additionalAttributes.status": [ "active" ] } } } }, { "bool": { "must_not": [ { "nested": { "path": "additionalAttributes", "query": { "exists": { "field": "additionalAttributes.status" } } } } ] } } ] } } } } ] }
- 切换查询目标
把原来所有针对person索引的查询,改为查询person_active别名,别名会自动将过滤条件与原有查询结合,只返回符合要求的文档。
解决方案2:全局搜索模板
如果不想切换索引别名,可创建一个全局搜索模板,将过滤逻辑作为固定部分嵌入,原有查询作为参数传入:
- 创建搜索模板
POST /_scripts/person_active_search { "script": { "lang": "mustache", "source": """ { "query": { "bool": { "must": [ {{#query}}{{query}}{{/query}} ], "filter": { "bool": { "should": [ { "nested": { "path": "additionalAttributes", "query": { "terms": { "additionalAttributes.status": [ "active" ] } } } }, { "bool": { "must_not": [ { "nested": { "path": "additionalAttributes", "query": { "exists": { "field": "additionalAttributes.status" } } } } ] } } ] } } } } } """ } }
- 通过模板执行查询
将原有查询作为参数传入模板,例如原查询为{"match": {"name": "张三"}},则执行:
POST /person/_search/template { "id": "person_active_search", "params": { "query": {"match": {"name": "张三"}} } }
这种方式只需修改查询的调用形式,无需改动原有查询的逻辑内容。
内容的提问来源于stack exchange,提问作者Java2Avaj
相关产品推荐
相关产品推荐

