理论
Elastichsarch 建立在 Lucene 之上。每个分片只是一个 Lucene 索引。 Lucene 索引,如果简化的话,就是倒排索引。每个 Elasticsearch 索引都是一堆分片或 Lucene 索引。当您查询文档时,Elasticsearch 将子查询所有分片、合并结果并将其返回给您。当您将文档索引到 Elasticsearch 时,Elasticsearch 将使用公式计算应写入哪个分片文档
shard = hash(routing) % number_of_primary_shards
默认情况下,Elasticsearch 使用文档id 作为路由。如果您指定routing 参数,它将被使用而不是id。您可以在搜索查询和索引、删除或更新文档的请求中使用routing 参数。
默认作为哈希函数使用MurmurHash3
示例
使用 3 个分片创建索引
$ curl -XPUT localhost:9200/so -d '
{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 0
}
}
}'
索引文件
$ curl -XPUT localhost:9200/so/question/1 -d '
{
"number" : 47011047,
"title" : "need elasticsearch index sharding explanation"
}'
无路由查询
$ curl "localhost:9200/so/question/_search?&pretty"
响应
查看_shards.total - 这是被查询的分片数量。另请注意,我们找到了文档
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 3,
"successful" : 3,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [
{
"_index" : "so",
"_type" : "question",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"number" : 47011047,
"title" : "need elasticsearch index sharding explanation"
}
}
]
}
}
使用正确的路由查询
$ curl "localhost:9200/so/question/_search?explain=true&routing=1&pretty"
响应
_shards.total 现在是 1,因为我们指定了路由,elasticsearch 知道要向哪个分片请求文档。使用参数explain=true 我要求elasticsearch 给我有关查询的更多信息。注意hits._shard - 它设置为[so][2]。这意味着我们的文档存储在so索引的第二个分片中。
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [
{
"_shard" : "[so][2]",
"_node" : "2skA6yiPSVOInMX0ZsD91Q",
"_index" : "so",
"_type" : "question",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"number" : 47011047,
"title" : "need elasticsearch index sharding explanation"
},
...
}
路由不正确的查询
$ curl "localhost:9200/so/question/_search?explain=true&routing=2&pretty"
响应
_shards.total 再次 1. 但是 Elasticsearch 没有向我们的查询返回任何内容,因为我们指定了错误的路由并且 Elasticsearch 查询了没有文档的分片。
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"hits" : {
"total" : 0,
"max_score" : null,
"hits" : [ ]
}
}
其他信息