定制路由允许你将同一个路由值的多篇文档归集到单个分片中,搜索的时候可以在索引分片的子集上进行。需要注意两方面:1. 在索引文档的时候挑选合适的路由值 2. 在执行查询的时候重用这些路由值。
默认是id,手动指定需要在URL中指定routing参数。
POST /users/_doc?routing=bbb
{
"name":"bbb",
"city":"BeiJing"
}
若插入文档时加入路由,根据id查询时必须加路由,否则有可能查不到文档
路由策略
挑选拥有足够基数的值,能够使索引在不同分片中分布比较均匀。
搜索时根据路由查询,这样就限制了搜索请求的查询的范围,对于有很多分片的索引来说可以用来提升性能。
GET /users/_search?routing=aaa,bbb
查看搜索在哪些分片执行
GET /users/_search_shards?routing=aaa
Response
{
"nodes" : {
"azcnDjEQRQWLcxQfsiXVbw" : {
"name" : "474107a2f2be",
"ephemeral_id" : "V7LRECMpSeGZhL9vdmBHgA",
"transport_address" : "172.17.0.2:9300",
"attributes" : {
"ml.machine_memory" : "1677721600",
"xpack.installed" : "true",
"transform.node" : "true",
"ml.max_open_jobs" : "20",
"ml.max_jvm_size" : "838860800"
}
}
},
"indices" : {
"users" : { }
},
"shards" : [
[
{
"state" : "STARTED",
"primary" : true,
"node" : "azcnDjEQRQWLcxQfsiXVbw",
"relocating_node" : null,
"shard" : 0,
"index" : "users",
"allocation_id" : {
"id" : "x0zFEmGKR6GfaWYItHeIXg"
}
}
]
]
}
配置路由
可以设置为所有文档定制路由,并拒绝索引没有定制路由的索引。
PUT /city
{
"mappings": {
"_routing": {
"required": true
},
"properties": {
"country":{
"type": "keyword"
},
"province":{
"type": "keyword"
}
}
}
}
索引文档时没加路由会报错
{
"error" : {
"root_cause" : [
{
"type" : "routing_missing_exception",
"reason" : "routing is required for [city]/[_doc]/[1]",
"index_uuid" : "_na_",
"index" : "city"
}
],
"type" : "routing_missing_exception",
"reason" : "routing is required for [city]/[_doc]/[1]",
"index_uuid" : "_na_",
"index" : "city"
},
"status" : 400
}