Application Programming Interface (API) in web is a group of function calls or other programming instructions to access the software component in that particular web application. For example, Facebook API helps a developer to create applications by accessing data or other functionalities from Facebook; it can be date of birth or status update.
Elasticsearch provides a REST API, which is accessed by JSON over HTTP. Elasticsearch uses some conventions which we shall discuss now.
Multiple Indices
Most of the operations, mainly searching and other operations, in APIs are for one or more than one indices. This helps the user to search in multiple places or all the available data by just executing a query once. Many different notations are used to perform operations in multiple indices. We will discuss a few of them here in this chapter.
Comma Separated Notation
POST /index1,index2,index3/_search
Request Body
{
"query":{
"query_string":{
"query":"any_string"
}
}
}
Response
JSON objects from index1, index2, index3 having any_string in it.
_all Keyword for All Indices
POST /_all/_search
Request Body
{
"query":{
"query_string":{
"query":"any_string"
}
}
}
Response
JSON objects from all indices and having any_string in it.
Wildcards ( * , + , –)
POST /school*/_search
Request Body
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
Response
JSON objects from all indices which start with school having CBSE in it.
Alternatively, you can use the following code as well −
POST /school*,-schools_gov /_search
Request Body
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
Response
JSON objects from all indices which start with “school” but not from schools_gov and having CBSE in it.
There are also some URL query string parameters −
- ignore_unavailable − No error will occur or no operation will be stopped, if the one or more index(es) present in the URL does not exist. For example, schools index exists, but book_shops does not exist.
POST /school*,book_shops/_search
Request Body
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
Request Body
{
"error":{
"root_cause":[{
"type":"index_not_found_exception", "reason":"no such index",
"resource.type":"index_or_alias", "resource.id":"book_shops",
"index":"book_shops"
}],
"type":"index_not_found_exception", "reason":"no such index",
"resource.type":"index_or_alias", "resource.id":"book_shops",
"index":"book_shops"
},"status":404
}
Consider the following code −
POST /school*,book_shops/_search?ignore_unavailable = true
Request Body
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
Response (no error)
JSON objects from all indices which start with school having CBSE in it.
allow_no_indices
true value of this parameter will prevent error, if a URL with wildcard results in no indices. For example, there is no index that starts with schools_pri −
POST /schools_pri*/_search?allow_no_indices = true
Request Body
{
"query":{
"match_all":{}
}
}
<h3