Elasticsearch条件查询嵌套数组

时间:2019-12-27 21:42:46

标签: elasticsearch

使用以下文档,我试图执行Elasticsearch关键字查询,有条件地从搜索范围中排除字段数据。这可能吗?

{
  "Name":"doc1",
  "UserData":[
      {
         "EnteredBy":"Eric",
         "Description":"Desc entered by Eric, abc"
      },
      {
         "EnteredBy":"Alex",
         "Description":"Desc entered by Alex, def"
      }
   ]
}

我需要的Elasticsearch查询将允许我在整个文档中进行搜索,只是它应从EnteredBy与指定用户不匹配的UserData项中排除。

以下查询将返回结果:

User:Eric doc1
User:Eric abc
User:Alex doc1
User:Fred doc1

以下查询不会返回结果:

User:Eric def
User:Fred def

到目前为止,我所做的所有事情最终都基于适用于指定用户的UserData节点的存在来过滤内容。我想不出一种方法,只有在EnteredBy字段匹配时,才指定要搜索的字段。

如果可以解决问题,我可以重组文档。

编辑1

索引。

PUT index1
{
  "settings": {
    "number_of_shards": 2,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties" : {
      "UserData" : {
        "type":"nested"
      },
      "Name": {
        "type":"text"
      }
    }
  }
}

编辑2

下面的查询提供了我需要的结果,除了子实体,我必须在特定的字段中进行搜索。如果我将嵌套搜索的第二个条件更改为query_string搜索,则它不再使用EnteredBy条件。

GET index1/_search
{
 "query": {
      "bool": { 
        "should": [
        {
          "nested": 
          {
               "path": "UserData",
               "query": {
                  "bool": {
                    "must": [{
                      "match": {
                        "UserData.EnteredBy": "Eric"
                      }},
                      {
                        "match": {
                        "UserData.Description": "def"
                      }
                    }]

                  }
                }
          }
        },
        { 
          "query_string": 
          { 
            "query": "doc1x" 
          }

        }
      ]
     }
  }
}

1 个答案:

答案 0 :(得分:1)

此查询似乎正在运行。我想我回答了我自己的问题。

GET index1/_search
{
 "query": {
      "bool": { 
        "should": [
        {
          "nested": 
          {
               "path": "UserData",
               "query": {
                  "bool": {
                    "must": [{
                      "match": {
                        "UserData.EnteredBy": "Eric"
                      }},
                      {
                        "query_string": {
                        "query": "def"
                      }
                    }]

                  }
                }
          }
        },
        { 
          "query_string": 
          { 
            "query": "doc1" 
          }

        }
      ]
     }
  }
}