MST
星途 面试题库

面试题:ElasticSearch过滤上下文智能筛选方法之高级难度题

在复杂的ElasticSearch索引结构中,存在多层嵌套文档,例如一个“orders”索引,每个订单文档包含“customer”信息以及“order_items”数组,“order_items”数组中的每个元素又包含“product”及其“attributes”。现在要筛选出所有购买了具有特定属性(如“color”: “red”)产品的订单,且客户所在城市为“New York”,请阐述实现思路并写出完整的ElasticSearch DSL查询语句。
24.1万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 利用bool查询来组合多个条件。
  2. bool查询的must子句中,分别添加针对客户城市和订单商品属性的查询条件。
  3. 对于多层嵌套结构,使用nested查询来深入到嵌套文档内部进行匹配。

ElasticSearch DSL查询语句

{
    "query": {
        "bool": {
            "must": [
                {
                    "nested": {
                        "path": "order_items",
                        "query": {
                            "nested": {
                                "path": "order_items.product.attributes",
                                "query": {
                                    "bool": {
                                        "must": [
                                            {
                                                "match": {
                                                    "order_items.product.attributes.color": "red"
                                                }
                                            }
                                        ]
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "match": {
                        "customer.city": "New York"
                    }
                }
            ]
        }
    }
}