ElasticSearch从列表中查询以包含X并包含X以外的内容

2024-06-12 00:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

假设在Elasticsearch中有一个字段“ListNames”,它提供字典列表。每本词典中的一个关键字是“人”。我的目标是查询/过滤所有相关的配置文件,其中“ListNames.People”包含“Adam”并且包含一个不是“Adam”的名称。如果没有所有可能的名字的详细列表(因为有很多),我怎么能做到这一点?提前谢谢你的帮助

下面的代码显示了我尝试过的post的示例

#Note: this returns profiles with ONLY Adam contained in the ListNames.
post_data = {
    "size": 30,
    "query": {
        'match':{
            'ListNames.People':'Adam'
        }
    }
}



#################
post_data = {
    "size": 30,
    "query": {
        'bool': {
            'should': [{
                'match': {
                    'ListNames.People': 'Adam'
                }
            }],
            'must_not':[
                {'match':{'ListNames.People':'Adam'}}
            ]
        }
    }
}
###################
post_data = {
    "size": 30,
    "query": {
        'bool': {
            'must': [{
                'match': {
                    'ListNames.People': 'Adam'
                }
            }],
            'must_not':[
                {'match':{'ListNames.People':'Adam'}}
            ]
        }
    }
}

第一个post只返回包含Adam的结果,这是不需要的,另外两个post返回空的


Tags: 列表datasize字典matchnotelasticsearchquery
1条回答
网友
1楼 · 发布于 2024-06-12 00:25:41

评论讨论后更新

你必须使用无痛药物来检查这种情况。请注意,使用脚本可能会导致性能下降

查询将是:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "ListNames.People": "Adam"
          }
        },
        {
          "script": {
            "script": {
              "source": "for(int i = 0; i < doc['ListNames.People'].length; i++) { if(doc['ListNames.People'][i] != params.person) { return true; }} return false;",
              "lang": "painless",
              "params": {
                "person": "Adam"
              }
            }
          }
        }
      ]
    }
  }
}

相关问题 更多 >