MST

星途 面试题库

面试题:ElasticSearch 条件过滤的嵌套文档与聚合应用

在 ElasticSearch 索引中有嵌套文档结构,比如一个订单索引,每个订单文档包含订单基本信息以及嵌套的订单项数组。订单项包含 'item_name'(商品名称)、'quantity'(数量)、'subtotal'(小计)字段。要求查询出所有订单项中商品名称包含 'book' 且至少有一个订单项小计大于 50 的订单,并按订单总价降序排列,同时计算出每个订单的总订单项数量,用 ElasticSearch 的查询 DSL 语法实现该需求。
34.9万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试
{
    "query": {
        "bool": {
            "must": [
                {
                    "nested": {
                        "path": "order_items",
                        "query": {
                            "bool": {
                                "must": [
                                    {
                                        "wildcard": {
                                            "order_items.item_name": "*book*"
                                        }
                                    },
                                    {
                                        "range": {
                                            "order_items.subtotal": {
                                                "gt": 50
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    }
                }
            ]
        }
    },
    "sort": [
        {
            "total_price": {
                "order": "desc"
            }
        }
    ],
    "aggs": {
        "total_order_items_count": {
            "nested": {
                "path": "order_items"
            },
            "aggs": {
                "count": {
                    "value_count": {
                        "field": "order_items.item_name"
                    }
                }
            }
        }
    }
}

假设订单文档结构中订单基本信息字段total_price表示订单总价,order_items为嵌套的订单项数组。实际使用时请根据真实的字段名称替换。