查询嵌套对象

时间:2016-02-15 15:18:37

标签: search elasticsearch nested

只是为了让事情清楚,第一天与Elastic一起工作......转向问题。

我开始使用

创建索引
curl -XPUT "http://localhost:9200/users" -d'
{
   "mappings": {
      "user": {
         "properties": {
            "education": {
               "type": "nested"
            },
            "job": {
               "type": "nested"
            }
         }
      }
   }
}'

然后

curl -XPOST "http://localhost:9200/users/user/" -d'
   {
      "name": "User A",
      "education": [
         {
            "school": "School A1",
            "course": "Course A1"
         },
         {
            "school": "School A2",
            "course": "Course A2"
         }
      ]
   }'

我现在面临的问题是查询部分。我试图通过以下方式获得结果:

curl -XPOST "http://localhost:9200/users/user/_search?pretty" -d'
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "nested": {
               "path": "education",
               "filter": {
                  "bool": {
                     "must": [
                        {
                           "term": {
                              "education.school": "School A1"
                           }
                        }
                     ]
                  }
               }
            }
         }
      }
   }
}'

但没有任何回报。

2 个答案:

答案 0 :(得分:1)

根据您提供的映射,school字段为analyzed。 分析表示文本School A将在空格上拆分,并将标记为SchoolA。 您正在使用寻找确切术语的term query进行搜索。关于term query研究here

您可以Query_string使用default_operator作为AND

curl -XPOST "http://localhost:9200/users/user/_search?pretty" -d'
{
  "query": {
  "filtered": {
     "query": {
        "match_all": {}
     },
     "filter": {
        "nested": {
           "path": "education",
           "filter": {
              "bool": {
                 "must": [
                    {
                       "query": {
                          "query_string": {
                             "default_field": "education.school",
                             "query": "School A1",
                             "default_operator": "AND"
                          }
                       }
                    }
                 ]
              }
             }
        }
     }
     }
    }
 }'

答案 1 :(得分:0)

离开我的2美分。我会避免使用filtered查询,因为它在最新版本的ES中被弃用Check this

我只是在不使用filtered query

的情况下重写上述查询
curl -XPOST "http://localhost:9200/users/user/_search?pretty" -d'
{
   "query": {
      "nested": {
         "path": "education",
         "query": {
            "bool": {
               "must": [
                  {
                     "query_string": {
                        "default_field": "education.school",
                        "query": "School A1",
                        "default_operator": "AND"
                     }
                  }
               ]
            }
         }
      }
   }
}'

我跟着this doc写了上面的查询。