MST
星途 面试题库

面试题:ElasticSearch索引API自定义路由策略应用

假设你正在处理一个电商订单数据的索引需求,每个订单都有一个店铺ID。为了实现同一店铺的订单尽量存储在同一分片上,以提高查询效率,你将如何设计并应用自定义路由策略?请给出具体实现思路和关键代码示例。
10.9万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 选择合适的数据库:以Elasticsearch为例,它支持自定义路由。
  2. 确定路由字段:使用店铺ID作为路由字段,因为要让同一店铺的订单在同一分片。
  3. 配置索引:在创建索引时指定路由字段。
  4. 写入数据:在写入订单数据时,将店铺ID作为路由参数传递,确保数据按要求分布。

关键代码示例(以Python和Elasticsearch为例)

from elasticsearch import Elasticsearch

# 连接Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

# 创建索引并指定路由字段
index_name = 'ecommerce_orders'
body = {
    "settings": {
        "number_of_shards": 3,
        "number_of_replicas": 1
    },
    "mappings": {
        "properties": {
            "order_id": {"type": "keyword"},
            "store_id": {"type": "keyword"},
            "order_info": {"type": "text"}
        }
    }
}
es.indices.create(index=index_name, body=body)

# 写入订单数据,使用store_id作为路由
order = {
    "order_id": "12345",
    "store_id": "store_1",
    "order_info": "Sample order info"
}
es.index(index=index_name, body=order, routing=order["store_id"])