Java最全全文检索工具elasticsearch:第三章: Java程序中的应用,Alibaba技术官内部私藏MySQL笔记分享
在Java程序中使用Elasticsearch,你需要依赖Elasticsearch的Java客户端。以下是一个基本的例子,展示如何在Java程序中使用Elasticsearch客户端执行基本操作,如索引文档、搜索文档和删除文档。
首先,添加Elasticsearch Java客户端的依赖到你的项目中,例如使用Maven:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.0</version>
</dependency>
以下是一个简单的Java程序,演示了如何使用Elasticsearch客户端:
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.index.get.GetRequest;
import org.elasticsearch.index.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
public class ElasticsearchExample {
public static void main(String[] args) throws IOException {
// 初始化Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
// 索引文档
IndexRequest indexRequest = new IndexRequest("posts", "_doc", "1");
indexRequest.source("title", "Some title", "content", "Some content");
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 获取文档
GetRequest getRequest = new GetRequest("posts", "_doc", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
// 搜索文档
SearchRequest searchRequest = new SearchRequest("posts");
searchRequest.source().query(QueryBuilders.matchQuery("title", "Some title"));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 删除文档
DeleteRequest deleteRequest = new DeleteRequest("posts", "_doc", "1");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
评论已关闭