📅  最后修改于: 2023-12-03 14:40:57.290000             🧑  作者: Mango
Elasticsearch是一个基于Lucene搜索引擎构建的开源搜索引擎。在Java中使用Elasticsearch时,可以使用Elasticsearch Java客户端。本文介绍如何在Java中添加Elasticsearch Java客户端依赖。
通过Gradle添加Elasticsearch Java客户端依赖,需要修改build.gradle
文件:
dependencies {
implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.15.0'
}
通过Maven添加Elasticsearch Java客户端依赖,需要修改pom.xml
文件:
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.15.0</version>
</dependency>
</dependencies>
以下是使用Elasticsearch Java客户端进行搜索的示例代码:
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
public class ElasticsearchJavaClientExample {
private static final String HOST_NAME = "localhost";
private static final int PORT = 9200;
private static final String INDEX_NAME = "my_index";
public static void main(String[] args) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(HOST_NAME, PORT, "http")));
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("title", "java"));
searchSourceBuilder.from(0);
searchSourceBuilder.size(5);
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);
client.close();
}
}
以上是添加Elasticsearch Java客户端依赖和使用示例代码的介绍。用户可以根据自己的需求来使用Elasticsearch Java客户端进行搜索。