简体   繁体   English

修复简单的Elasticsearch查询

[英]Fixing a Simple Elasticsearch Query

I have below data: 我有以下数据:

{
   "results":[
      {
         "ID":"1",
         "products":[
            {
               "product":"car",
               "number":"5"
            },
            {
               "product":"computer",
               "number":"212"
            }
         ]
      },
      {
         "ID":"2",
         "products":[
            {
               "product":"car",
               "number":"9"
            },
            {
               "product":"computer",
               "number":"463"
            },
            {
               "product":"bicycle",
               "number":"5"
            }
         ]
      }
   ]
}

And my query is below: 我的查询如下:

{  
   "query":{  
      "bool":{  
         "must":[  
            {  
               "wildcard":{  
                  "results.products.product":"*car*"
               }
            },
            {  
               "wildcard":{  
                  "results.products.number":"*5*"
               }
            }
         ]
      }
   }
}

What I expect is to get only ID1. 我期望只获得ID1。 Because only it has a product with { "product":"car", "number":"5" } record. 因为它只有一个产品{{product“:”car“,”number“:”5“}记录。 But what I get is both ID1 and ID2 because ID2's first record has "product":"car" and third record has "number":"5" records separately. 但我得到的是ID1和ID2,因为ID2的第一个记录有“产品”:“汽车”和第三个记录分别有“数字”:“5”记录。

How can I fix this query? 我该如何修复此查询?

You need to define your products as a nested type when creating mapping. 创建映射时,需要将产品定义为嵌套类型 Try with following mapping example: 尝试使用以下映射示例:

PUT http://localhost:9200/indexname

{
  "mappings": {
     "typename": {
        "properties": {
           "products" : {
              "type" : "nested"
            }
          }
       }
    }
 }

Then you can use nested queries to match entire elements of your array - just as you need to. 然后,您可以使用嵌套查询来匹配数组的整个元素 - 就像您需要的那样。

{
  "query": {
    "nested": {
      "path": "products",
      "query": {
        "bool": {
          "must": [
            { "wildcard": { "products.product": "*car*" }},
            { "wildcard": { "products.number":  "*5*" }} 
          ]
        }
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM