用最新的 Elasticsearch Java client 8.0 来创建索引并搜索
人赞同了该文章篇文章,我来详细地描述如何使用最新的 Elasticsearch Java client 8.0 来创建索引并进行搜索。最新的 Elasticsearch Java client API 和之前的不同。在之前的一些教程中,我们使用 High Level API 来进行操作。在官方文档中,已经显示为 deprecated。前提条件
版本托管在 Maven Central 上。 如果你正在寻找 SNAPSHOT 版本,可以从 https://snapshots.elastic.co/maven/ 获得 Elastic Maven 快照存储库。
新的 Java client API 具有一下的优点:
如果你还没有安装好自己的 Elasticsearch 及 Kibana 的话,请参阅我之前的文章:
如果你想在 Elastic Stack 8.0 上试用的话。你可以参阅文章 “ Elastic Stack 8.0 安装 - 保护你的 Elastic Stack 现在比以往任何时候都简单 ”。在本文章中,我们不启用 HTTPS 的访问。你需要查看文章中 “如何配置 Elasticsearch 只带有基本安全” 这个部分。我们为 Elasticsearch 配置基本安全。
在今天的展示中,我将使用 Maven 项目来进行展示尽管 gradle 也可以。为了方便大家的学习,我把我创建的项目上传到 github 上 GitHub - liu-xiao-guo/ElasticsearchJava-search8
首先,我们的 pom.xml 文件如下:
4.0.0
org.example
ElasticsearchJava-search8
1.0-SNAPSHOT
8
8
8.0.1
co.elastic.clients
elasticsearch-java
${elastic.version}
com.fasterxml.jackson.core
jackson-databind
2.12.3
jakarta.json
jakarta.json-api
2.0.1
如上所示,我们使用了 8.0.1 的版本。你也可以使用在地址 Maven Central Repository Search 上的最新版本 8.1.1。
接下来,我们创建一个叫做 Product.java 的文件:
public class Product {
private String id;
private String name;
private int price;
public Product() {
}
public Product(String id, String name, int price) {
this.id = id;
this.name = name;
this.price = price;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
我们再接下来创建 ElasticsearchJava.java 文件:
import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import java.io.IOException;
public class ElasticsearchJava {
private static ElasticsearchClient client = null;
private static ElasticsearchAsyncClient asyncClient = null;
private static synchronized void makeConnection() {
// Create the low-level client
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
RestClient restClient = builder.build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// And create the API client
client = new ElasticsearchClient(transport);
asyncClient = new ElasticsearchAsyncClient(transport);
}
public static void main(String[] args) throws IOException {
makeConnection();
// Index data to an index products
Product product = new Product("abc", "Bag", 42);
IndexRequest
在上面,代码也非常直接。我们使用如下的代码来连接到 Elasticsearch:
private static synchronized void makeConnection() {
// Create the low-level client
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
RestClient restClient = builder.build();
// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// And create the API client
client = new ElasticsearchClient(transport);
asyncClient = new ElasticsearchAsyncClient(transport);
}
在上面,我们使用 elastic 这个超级用户来进行访问。它的密码是 password。这个在实际的使用中,需要根据自己的情况来进行设置。
在下面,我们使用如下的两种格式来写入数据到 products 索引中:
// Index data to an index products
Product product = new Product("abc", "Bag", 42);
IndexRequest
上述的写入类似于在 Kibana 中输入如下的指令:
PUT products/_doc/abc
{
"id": "abc",
"name": "Bag",
"price": 42
}
我们可以在 Kibana 中进行查看:
GET products/_search
上面的命令显示:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "products",
"_id" : "abc",
"_score" : 1.0,
"_source" : {
"id" : "abc",
"name" : "Bag",
"price" : 42
}
},
{
"_index" : "products",
"_id" : "efg",
"_score" : 1.0,
"_source" : {
"id" : "efg",
"name" : "Bag",
"price" : 42
}
}
]
}
}
显然我们写入的数据是成功的。
接下来,我使用了如下的两种格式来进行搜索:
// Search for a data
TermQuery query = QueryBuilders.term()
.field("name")
.value("bag")
.build();
SearchRequest request = new SearchRequest.Builder()
.index("products")
.query(query._toQuery())
.build();
SearchResponse search =
client.search(
request,
Product.class
);
for (Hit hit: search.hits().hits()) {
Product pd = hit.source();
System.out.println(pd);
}
SearchResponse search1 = client.search(s -> s
.index("products")
.query(q -> q
.term(t -> t
.field("name")
.value(v -> v.stringValue("bag"))
)),
Product.class);
for (Hit hit: search1.hits().hits()) {
Product pd = hit.source();
System.out.println(pd);
}
这个搜索相当于:
GET products/_search
{
"query": {
"term": {
"name": {
"value": "bag"
}
}
}
}
上面的搜索结果为:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 0.18232156,
"hits" : [
{
"_index" : "products",
"_id" : "abc",
"_score" : 0.18232156,
"_source" : {
"id" : "abc",
"name" : "Bag",
"price" : 42
}
},
{
"_index" : "products",
"_id" : "efg",
"_score" : 0.18232156,
"_source" : {
"id" : "efg",
"name" : "Bag",
"price" : 42
}
}
]
}
}
Java 代码输出的结果为:
Product{id='abc', name='Bag', price=42}
Product{id='efg', name='Bag', price=42}
Product{id='abc', name='Bag', price=42}
Product{id='efg', name='Bag', price=42}
我们使用如下的代码来简化一个复杂的 DSL:
// Splitting complex DSL
TermQuery termQuery = TermQuery.of(t ->t.field("name").value("bag"));
SearchResponse search2 = client.search(s -> s
.index("products")
.query(termQuery._toQuery()),
Product.class
);
for (Hit hit: search2.hits().hits()) {
Product pd = hit.source();
System.out.println(pd);
}
同样上面的输出结果为:
Product{id='abc', name='Bag', price=42}
Product{id='efg', name='Bag', price=42}
最后,使用了一个 aggregation:
// Creating aggregations
SearchResponse search3 = client.search( b-> b
.index("products")
.size(0)
.aggregations("price-histo", a -> a
.histogram(h -> h
.field("price")
.interval(20.0)
)
),
Void.class
);
long firstBucketCount = search3.aggregations()
.get("price-histo")
.histogram()
.buckets().array()
.get(0)
.docCount();
System.out.println("doc count: " + firstBucketCount);
}
上面的 aggregation 相当于如下的请求:
GET products/_search
{
"size": 0,
"aggs": {
"price-histo": {
"histogram": {
"field": "price",
"interval": 50
}
}
}
}
它的响应结果为:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"price-histo" : {
"buckets" : [
{
"key" : 0.0,
"doc_count" : 2
}
]
}
}
}
我们的 Java 代码的输出结果为:
doc count: 2
1、背景介绍一个搜索服务一般基于es集群构建,这个es集群承载着多种结构的索引结构,每个索引数据结构不一样,容量不一样,请求数也不一样。虽然官方说他们是均匀分布在es集群中的各个节点…
hupper
在文章 Elasticsearch 入门学习 中介绍了 Elasticsearch 的基础概念以及一些常用的 API。这篇文章是继续对 Elasticsearch 中一些高级的搜索功能的学习和总结:搜索的相关性以及算分机制 什…
张佃鹏发表于Mysql...
良月柒
王知无发表于大数据面试...