Elastic Search

Using Elasticsearch to Check If an Alias Exists

In this brief article, we will show you how to use the Elasticsearch alias API to check if an alias exists in the cluster. It is good to ensure that an index exists before using it in a query. It can also be beneficial to prevent one alias from referencing a similar index to prevent name collisions.

Let’s dive in.

Request Syntax

The following block shows the request alias for the API endpoint:

HEAD _alias/<alias>
HEAD <target>/_alias/<alias>

The request accepts the following parameters:

  1. <alias> – Specifies a list of aliases to check (as comma-separated values). You can also specify an asterisk as a wildcard character to denote all aliases in the cluster.
  2. <target> – Specifies a list of data streams or indices used to limit the target request. You can also use an asterisk or _all wildcards.

Request Responses

The request returns the corresponding HTTP status codes as shown:

  1. 200 – All the alias specified exists in the cluster.
  2. 404 – One or more aliases do not exist in the cluster.

Example

Let us illustrate how to use this API. Suppose we have an index called Netflix that contains movies and TV Shows.

We can start by creating an alias for the index as shown in the following:

curl -XPOST "http://localhost:9200/_aliases" -H "kbn-xsrf: reporting" -H "Content-Type: application/json" -d'
{
  "actions": [
    {
      "add": {
        "index": "netflix",
        "alias": "ntflx"
      }
    }
  ]
}'

We can then check if the alias exists as shown in the following:

curl -XHEAD "http://localhost:9200/_alias/ntflx" -H "kbn-xsrf: reporting"

The resulting output is as follows:

200 - OK

If we request a non-existent alias:

curl -XHEAD "http://localhost:9200/_alias/nf" -H "kbn-xsrf: reporting"

The previous request should return a 404 status code as:

{
  "statusCode": 404,
  "error": "Not Found",
  "message": "404 - Not Found"
}

In this case, the index does not exist in the cluster.

We can also check the multiple aliases as shown in the following:

curl -XHEAD "http://localhost:9200/_alias/ntflx,netflix_alias" -H "kbn-xsrf: reporting"

The resulting output is as follows:

200 - OK

In this case, we can verify that both aliases exist in the cluster.

If one alias does not exist, the request returns a 404-status code.

Conclusion

In this post, we discussed how to use the Elasticsearch alias API with the HEAD method to check if a specific alias exists in the cluster.

Thanks for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list