The indexed
document in Elasticsearch can be searched with matching criteria using various
Query DSLs available. We can define the fields to be searched and the kind of data
we require. There is variety of search options available with Elasticsearch
which we will be discussing in upcoming topics.
In this post,
let’s see how search works and how to do it using REST service and Java API.
Search index using REST API:
1. URI search
$ curl -XGET
'http://localhost:9200/simplyjava/user/_search?q=userName:steve’
The above search
will retrieve all the users who have name “steve”. It will look up for complete
word and partial matches will not be retrieved.
Response:
{
"took": 7,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1.4054651,
"hits": [
{
"_index": "simplyjava",
"_type":
"user",
"_id": "4",
"_score": 1.4054651,
"_source": {
"userName":
"Steve",
"place":
"Texas",
"age": "29",
"location": {
"lat":
"80.234",
"lon":
"-120.4"
}
}
}
]
}
}
2.
Search with request body
The search can also be made by building
request body using various query DSL statements in Elasticsearch. Below is an
example of sending data as part of request body.
$ curl -XGET
'http://localhost:9200/simplyjava/user/_search –d’{
"query": {
"match ": {
"userName": "
steve"
}
}
}’
Search
index using Java API:
Below is the sample code
snippet to build the search request and invoke the elasticsearch API to
retrieve the results.
Code
QueryBuilder qb1 =
QueryBuilders.matchQuery("userName", "steve");
SearchResponse response =
client.prepareSearch("simplyjava")
.setQuery(qb1).execute().actionGet();
for (SearchHit hit :
response.getHits().getHits()) {
System.out.println(“Id
: “ + hit.getId());
System.out.println(“Source
: “+hit.getSourceAsString());
}
Output
Id : 4
Source : {
"userName":"Steve",
"place":"Texas",
"age":"29",
"location":{
"lat":"80.234",
"lon":"-120.4"
}
}
Note: We can also search for partial keywords
as well. It will be covered in future topics.
No comments:
Post a Comment