Elasticsearch 自 7.16 版本(2021年12月8日)推出 Elasticsearch Java API Client.Elasticsearch Java API 客户端为所有的 Elasticsearch API 提供请求和响应处理.

它将请求处理转给 Elasticsearch Low Level REST 客户端,这也是 High Level 被废弃而 Low Level REST 客户端依然健在的原因,Low Level REST 客户端负责处理 Http 连接建立和池化,重试机制等所有传输级别的问题.

  • 特点1:对象构造基于构建者模式( builder pattern).
  • 特点2:使用 lambda 构建嵌套对象,从而编写干净,富有表现力的 DSL 变得容易.
  • 特点3:应用程序类能自动映射为 Mapping.

创建 Elasticsearch Java 客户端

让我们先创建好 Elasticsearch Java 客户端:

RestClient restClient = RestClient.builder(HttpHost.create("http://localhost:9200")).build();ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);

现在,我们已准备好与 Elasticsearch 进行交互.接下来,我将给出3种查询示例.

Match查询

样例索引数据

{"columns" : [{"name" : "des","type" : "text"},{"name" : "name","type" : "text"},{"name" : "price","type" : "float"},{"name" : "sku","type" : "text"}],"rows" : [["旺仔牛比糖吃了炒鸡牛笔","旺仔牛比糖",6.66,"aabbcc555"],["农夫三拳有点甜","农夫三拳",3.0,"3344"]]}

DSL查询语句

POST /produces/_search{"query": {"match": {"name": {"query": "农夫三拳"}}}}

使用MatchQuery

MatchQuery matchQuery = MatchQuery.of(bd -> bd.field("name").query("农夫三拳"));Builder builder1 = new SearchRequest.Builder();builder1.index("produces").query(matchQuery._toQuery());System.out.println(matchQuery._toQuery());final SearchResponse<Produce> response1 = client.search(builder1.build(), Produce.class);System.out.println(response1.hits().hits());

使用lambda表达式

final SearchResponse<Produce> response2 = client.search(builder -> builder.index("produces").query(q -> q.match(t -> t.field("name").query("农夫三拳"))),Produce.class);System.out.println(response2.hits().hits());

使用 Query.Builder

Query.Builder queryBuilder = new Query.Builder();queryBuilder.match(bd -> bd.field("name").query("农夫三拳"));Builder searchRequestBuilder = new SearchRequest.Builder();Query query = queryBuilder.build();searchRequestBuilder.index("produces").query(query);System.out.println(query);final SearchResponse<Produce> response1 = client.search(searchRequestBuilder.build(), Produce.class);System.out.println(response1.hits().hits());