elasticsearchHow do I use Elasticsearch with Java?
Elasticsearch is a popular open-source search engine built on Apache Lucene. It enables you to store, search, and analyze big volumes of data quickly and in near real-time.
Using Elasticsearch with Java requires three steps:
- Install the Elasticsearch Java client: Add the following dependency to your project's pom.xml file:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
- Create an instance of the client:
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")
)
);
- Use the client to perform operations:
SearchRequest searchRequest = new SearchRequest("posts");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("title", "java"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
System.out.println("Total hits: " + hits.getTotalHits());
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
Output example
Total hits: 2
{"title": "Java 8 Streams", "content": "Java 8 Streams..."}
{"title": "Java 11 Features", "content": "Java 11 Features..."}
The code above creates an instance of the client, then uses it to perform a search request on the posts index. The search query looks for documents with the title containing the word java. The output of the code prints out the total number of hits and the source of each document that matched the query.
Helpful links
More of Elasticsearch
- How can I use elasticsearch zone awareness to improve my software development?
- How can I use Elasticsearch and Zabbix together for software development?
- How can I use YouTube to learn about Elasticsearch?
- How do I configure xpack.security.authc.realms in Elasticsearch?
- How do I use Elasticsearch with ZGC?
- How can I check the status of a yellow index in Elasticsearch?
- How do I set up an Elasticsearch Yum repository?
- How can I use Elasticsearch to diagnose "yellow" issues?
- How do I configure elasticsearch xpack.security.transport.ssl?
- How can I store and query zoned datetime values in Elasticsearch?
See more codes...