MST

星途 面试题库

面试题:ElasticSearch映射数据类型在复杂查询场景中的扩展应用

在ElasticSearch中,假设我们有一个包含产品信息的索引,其中产品描述字段使用了text类型。现在需要实现一个功能,能够根据产品描述中的关键词搜索,同时还要按照产品价格(price,使用number类型)进行过滤和排序。请描述如何通过合理设置映射数据类型以及编写相应的查询语句来实现这个功能。
15.3万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

1. 设置映射数据类型

在创建索引时,合理设置字段的数据类型。示例如下:

PUT product_index
{
    "mappings": {
        "properties": {
            "product_description": {
                "type": "text"
            },
            "price": {
                "type": "number"
            }
        }
    }
}

2. 编写查询语句

使用bool查询来组合关键词搜索和价格过滤,使用sort来按照价格排序。示例如下:

GET product_index/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "product_description": "关键词"
                    }
                }
            ],
            "filter": [
                {
                    "range": {
                        "price": {
                            "gte": 0, // 价格下限
                            "lte": 100 // 价格上限
                        }
                    }
                }
            ]
        }
    },
    "sort": [
        {
            "price": {
                "order": "asc" // 升序排序,可改为 "desc" 降序
            }
        }
    ]
}