实现思路
- 选择合适的数据库:以Elasticsearch为例,它支持自定义路由。
- 确定路由字段:使用店铺ID作为路由字段,因为要让同一店铺的订单在同一分片。
- 配置索引:在创建索引时指定路由字段。
- 写入数据:在写入订单数据时,将店铺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"])