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 with PostgreSQL?
- How can I use elasticsearch zone awareness to improve my software development?
- How can I perform a case-insensitive wildcard search using Elasticsearch?
- How can I use Elasticsearch to diagnose "yellow" issues?
- How do I configure the Xms and Xmx settings for Elasticsearch?
- How can I use an Elasticsearch template to index data?
- How do I use Elasticsearch with ZGC?
- How do I use ElasticSearch to zip files?
- How can I use Elasticsearch and ZFS together?
- How can I index XML data in Elasticsearch?
See more codes...