Checking if an index or type exists

A common pitfall error is to query for indices and types that don't exist. To prevent this issue, Elasticsearch gives the user the ability to check the index and type existence.

This check is often used during an application startup to create indices and types that are required for correct working.

Getting ready

You need an up-and-running Elasticsearch installation, as used in the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.

To execute curl via the command line, you need to install curl for your operative system.

To correctly execute the following commands, use the index created in the Creating an index recipe.

How to do it...

The HTTP method to check existence is HEAD. The URL format for checking an index is:

http://<server>/<index_name>/

The URL format for checking a type is:

http://<server>/<index_name>/<type>/

To check if an index exists, we will perform the steps given as follows:

  1. If we consider the index created in the  Creating an index  recipe, the call will be:
            curl -i -XHEAD 'http://localhost:9200/myindex/' 
    
  2. The -i curl options allows dumping the server headers.
  3. If the index exists, an HTTP status code 200 is returned, if missing, a 404. For checking if a type exists, we will perform the steps given as follows:
  4. If we consider the mapping created in the Putting a mapping in an index recipe, the call will be as follows:
            curl -i -XHEAD 'http://localhost:9200/myindex/order/' 
    
  5. If the index exists, an HTTP status code 200 is returned, if missing, a 404.

How it works...

This is a typical HEAD REST call to check existence. It doesn't return body response, but only the status code, which is the result status of the operation.

The most common status codes are:

  • 20X family if everything is okay
  • 404 if the resource is not available
  • 50X family if there are server errors

Tip

Before every action involved in indexing, generally on application startup, it's good practice to check if an index or type exists to prevent future failures.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.34.80