MST

星途 面试题库

面试题:ElasticSearch API下复杂条件搜索时如何精准格式化结果结构

假设有一个电商产品索引,其中包含产品名称、价格、类别、描述等字段。现在要求使用API搜索价格在某个区间内,且属于特定类别的产品,并将搜索结果格式化为自定义的结构,只包含产品名称、价格和简要描述(描述截取前100个字符)。请详细说明使用的API和具体实现步骤。
38.4万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试
  1. 选择API
    • 对于电商产品索引搜索,常用的API如Elasticsearch API。Elasticsearch是一个分布式、RESTful风格的搜索和数据分析引擎,非常适合处理此类搜索需求。
  2. 具体实现步骤(以Elasticsearch为例)
    • 数据准备
      • 确保电商产品数据已按照规定的格式(包含产品名称、价格、类别、描述等字段)正确索引到Elasticsearch中。例如,使用Elasticsearch的文档结构如下:
{
    "product_name": "示例产品名称",
    "price": 100,
    "category": "特定类别",
    "description": "这是一个很长的产品描述......"
}
  • 搜索请求
    • 使用Elasticsearch的search API来构建查询。查询体可以如下:
{
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "price": {
                            "gte": 50, // 价格区间下限
                            "lte": 200 // 价格区间上限
                        }
                    }
                },
                {
                    "term": {
                        "category": "特定类别"
                    }
                }
            ]
        }
    },
    "_source": ["product_name", "price", "description"]
}

这里使用bool查询的filter子句来同时满足价格区间和特定类别条件。_source指定返回的字段。

  • 结果处理
    • 接收到Elasticsearch返回的结果后,遍历结果列表。对于每个命中的文档,截取description字段的前100个字符:
import json
from elasticsearch import Elasticsearch

es = Elasticsearch()
response = es.search(index='your_index_name', body=above_query_body)
custom_results = []
for hit in response['hits']['hits']:
    source = hit['_source']
    description = source['description'][:100]
    custom_result = {
        "product_name": source['product_name'],
        "price": source['price'],
        "brief_description": description
    }
    custom_results.append(custom_result)
print(json.dumps(custom_results, indent=4))

上述Python代码使用Elasticsearch Python客户端,处理搜索结果并构建自定义结构。最终将自定义结构以JSON格式打印输出,满足题目要求的格式。

如果使用其他搜索API(如Solr等),实现思路类似,主要差异在于查询语法和API调用方式。例如Solr使用q参数构建查询,fl参数指定返回字段等。