Updated on 2024-11-29 GMT+08:00

Routing

When Elasticsearch writes data into a document, the document is routed to a segment of an index using a formula. The default formula is as follows:

shard_num = hash(_routing) % num_primary_shards

The value of the _routing field is the _id field by default. You can set the field to one that is frequently queried based on the service scenario. For example, the user ID and area can be used as routing fields. Unnecessary fragments can be filtered during query to speed up the query.

The following is an example data writing with route specified in security mode:

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"
}'

The following is an example of query with route not specified in security mode:

curl -XGET --tlsv1.2 --negotiate -k -u : "https://ip:httpport/my_index/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "title": "document"
    }
  }
}'

To query all fragments, run the following command:

{
  "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"
        }
      }
    ]
  }
}

To query data with route specified in security mode, run the following command:

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"
    }
  }
}'

To query only one shard, run the following command:

{
  "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"
        }
      }
    ]
  }
}