是否可以在ElasticSearch文档中过滤掉数组中的对象?

polhcujo  于 7个月前  发布在  ElasticSearch
关注(0)|答案(1)|浏览(73)

对于这样的文档:

{
    {
        "id": 1,
        "vehicle": "car",
        "equipment": [
            {
                "v_id": 11,
                "gps": false,
                "color": "yellow"
            }
        ]
    },
    {
        "id": 2,
        "vehicle": "bus",
        "equipment": [
            {
                "v_id": 34,
                "gps": false,
                "color": "red"
            },
            {
                "v_id": 99,
                "gps": false,
                "color": "yellow"
            },
            {
                "v_id": 10,
                "gps": true,
                "color": "red"
            }
        ]
    }
}

字符串
是否可以同时检索vehicle: busvehicle: car文档,然后在此基础上过滤掉不必要的equipment
例如,搜索巴士和汽车的预期结果,但结果中仅包含equipmentgps: true

{
    {
        "id": 1,
        "vehicle": "car",
        "equipment": []
    },
    {
        "id": 2,
        "vehicle": "bus",
        "equipment": [
            {
                "v_id": 10,
                "gps": true,
                "color": "red"
            }
        ]
    }
}

wfveoks0

wfveoks01#

如果设备的类型为nested,您可以添加一个伪nested查询,它将执行inner_hits检索:

DELETE test

PUT test
{
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "vehicle": {
        "type": "keyword"
      },
      "equipment": {
        "type": "nested",
        "properties": {
          "v_id": {
            "type": "long"
          },
          "gps": {
            "type": "boolean"
          },
          "color": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

PUT test/_bulk?refresh
{"index":{"_id": 1}}
{"id":1,"vehicle":"car","equipment":[{"v_id":11,"gps":false,"color":"yellow"}]}
{"index":{"_id": 2}}
{"id":2,"vehicle":"bus","equipment":[{"v_id":34,"gps":false,"color":"red"},{"v_id":99,"gps":false,"color":"yellow"},{"v_id":10,"gps":true,"color":"red"}]}

POST test/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "terms": {
            "vehicle": [
              "bus",
              "car"
            ]
          }
        },
        {
          "nested": {
            "path": "equipment",
            "query": {
              "term": {
                "equipment.gps": true
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  },
  "_source": {
    "excludes": "equipment"
  }
}

字符串

相关问题