更新时间:2024-11-29 GMT+08:00
路由(routing)
Elasticsearch写入文档时,文档会通过一个公式路由到一个索引中的一个分片上。默认公式如下:
shard_num = hash(_routing) % num_primary_shards
_routing字段的取值,默认是_id字段,可以根据业务场景设置经常查询的字段作为路由字段。例如可以考虑将用户id、地区作为路由字段,查询时可以过滤不必要的分片,加快查询速度。
安全模式下写入时指定路由:
curl -XPUT --tlsv1.2 --negotiate -k -u : "https://ip:httpport/my_index/my_type/1?routing=user1&refresh=true" -H 'Content-Type: application/json' -d' { "title": "This is a document" }'
安全模式下查询时不指定路由示例:
curl -XGET --tlsv1.2 --negotiate -k -u : "https://ip:httpport/my_index/_search?pretty" -H 'Content-Type: application/json' -d' { "query": { "match": { "title": "document" } } }'
需要查询所有的分片,返回结果:
{ "took" : 5, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 0.2876821, "hits" : [ { "_index" : "my_index", "_type" : "my_type", "_id" : "1", "_score" : 0.2876821, "_routing" : "user1", "_source" : { "title" : "This is a document" } } ] } }
安全模式下查询时指定路由示例:
curl -XGET --tlsv1.2 --negotiate -k -u : "https://ip:httpport/my_index/_search?routing=user1&pretty" -H 'Content-Type: application/json' -d' { "query": { "match": { "title": "document" } } }'
查询时只需要查询一个分片,查询结果:
{ "took" : 8, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 0.2876821, "hits" : [ { "_index" : "my_index", "_type" : "my_type", "_id" : "1", "_score" : 0.2876821, "_routing" : "user1", "_source" : { "title" : "This is a document" } } ] } }
父主题: 数据查询调优