搜索ElasticSearch中的数组元素

时间:2017-04-27 21:58:29

标签: elasticsearch

我试图在数组上搜索两个或多个值,只获取那些与所有单词匹配的值(AND CLAUSE)

一些例子:

   { "name" : "Chevrolet",
      "value" : [ "gasolina", "alcool", "diesel"]
   }    
   { "name" : "Fiat",
      "value" : [ "eletrica", "alcool"]
   }
   { "name" : "Honda",
      "value" : [ "diesel", "gasolina"]
   }

我的映射

{
  "mappings": {
    "cars": {
      "properties": {
        "name": {
          "type": "string"
        },
        "GasType": {
          "type": "nested",
          "properties": {
            "value": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

查询:

{
  "query": {
    "nested": {
      "path": "GasType",
      "query": {
        "bool": {
          "must": [
            { "match": {"GasType.value": "gasolina"}},
            { "match": {"GasType.value": "diesel"}}
          ]
        }
      }
    }
  }
}

我的回报总是空的,如果我改变了查询,我得到的所有那些包含“Gasolina”或“柴油” 我需要那些有“Gasolina”和“柴油”的人

1 个答案:

答案 0 :(得分:0)

您的测试数据与索引的映射不匹配。在您的测试数据中,我没有看到嵌套字段名称GasType。在任何情况下,以下对我来说都很合适:

DELETE test
PUT test
{
  "mappings": {
    "cars": {
      "properties": {
        "name": {
          "type": "string"
        },
        "GasType": {
          "type": "nested",
          "properties": {
            "value": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

POST test/cars/_bulk
{"index":{}}
{"name":"Chevrolet","GasType":{"value":["gasolina","alcool","diesel"]}}
{"index":{}}
{"name":"Fiat","GasType":{"value":["eletrica","alcool"]}}
{"index":{}}
{"name":"Honda","GasType":{"value":["diesel","gasolina"]}}
{"index":{}}
{"name":"Honda","GasType":{"value":["diesel"]}}

GET test/_search
{
  "query": {
    "nested": {
      "path": "GasType",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "GasType.value": "gasolina"
              }
            },
            {
              "match": {
                "GasType.value": "diesel"
              }
            }
          ]
        }
      }
    }
  }
}