Elasticsearch 是一个流行的开源搜索引擎,可以用于存储、搜索和分析大量的文本数据。以下是一些 Java Elasticsearch 常见操作示例:
连接到 Elasticsearch
使用 Elasticsearch 的 Java 客户端连接到 Elasticsearch 集群:
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
创建索引
使用 Java 客户端创建一个 Elasticsearch 索引:
CreateIndexRequest request = new CreateIndexRequest("myindex");
client.admin().indices().create(request).actionGet();
添加文档
使用 Java 客户端添加一个文档到 Elasticsearch 索引:
IndexResponse response = client.prepareIndex("myindex", "mytype", "1")
.setSource(jsonBuilder()
.startObject()
.field("title", "My first blog post")
.field("content", "This is my first blog post.")
.endObject())
.get();
搜索文档
使用 Java 客户端搜索 Elasticsearch 索引中的文档:
SearchResponse response = client.prepareSearch("myindex")
.setQuery(QueryBuilders.termQuery("title", "blog"))
.get();
删除索引
使用 Java 客户端删除 Elasticsearch 索引:
DeleteIndexRequest request = new DeleteIndexRequest("myindex");
client.admin().indices().delete(request).actionGet();