Elasticsearch - Java API(Lambda 表达式) 操作 ES7.16.0+、ES8.x 索引,文档;高级搜索(七)

阅读本文前可先参考

https://blog.csdn.net/MinggeQingchun/article/details/126618387

https://blog.csdn.net/MinggeQingchun/article/details/126762570

Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch服务进行访问

以 Elasticsearch7.16.0版本为例

1、创建空工程elasticsearch-demo,创建普通Java的maven模块elasticsearch-test

2、添加依赖

查看Elasticsearch官网文档

Installation | Elasticsearch Java API Client [7.16] | Elastic

<dependencies>

    <!-- elasticsearch -->
<!--    <dependency>-->
<!--      <groupId>org.elasticsearch</groupId>-->
<!--      <artifactId>elasticsearch</artifactId>-->
<!--      <version>7.16.0</version>-->
<!--    </dependency>-->

    <!-- elasticsearch 的客户端 -->
    <dependency>
      <groupId>co.elastic.clients</groupId>
      <artifactId>elasticsearch-java</artifactId>
      <version>7.16.0</version>
    </dependency>

    <!-- elasticsearch 依赖 2.x 的 log4j -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.17.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.17.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.3</version>
    </dependency>

    <!-- junit 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

一、Elasticsearch 客户端对象

Elasticsearch7.15版本之后,Elasticsearch官方将它的高级客户端 RestHighLevelClient 标记为弃用状态

同时推出了全新的Java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端

Elasticsearch Java API Client 支持除 Vector tile search API 和 Find structure API 之外的所有 Elasticsearch API。且支持所有API数据类型,并且不再有原始JsonValue属性。它是针对Elasticsearch8.0及之后版本的客户端

Elasticsearch Java API Client [8.4] | Elastic

(一)Java API Client连接(新版本)

Connecting | Elasticsearch Java API Client [7.16] | Elastic

The Java API Client is structured around three main components:

  • API client classes. These provide strongly typed data structures and methods for Elasticsearch APIs. Since the Elasticsearch API is large, it is structured in feature groups (also called “namespaces”), each having its own client class. Elasticsearch core features are implemented in the ElasticsearchClient class.
  • A JSON object mapper. This maps your application classes to JSON and seamlessly integrates them with the API client.
  • A transport layer implementation. This is where all HTTP request handling takes place.
// Create the low-level client
RestClient restClient = RestClient.builder(
    new HttpHost("localhost", 9200)).build();

// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
    restClient, new JacksonJsonpMapper());

// And create the API client
ElasticsearchClient client = new ElasticsearchClient(transport);

完整代码如下:

import co.elastic.clients.elasticsearch.ElasticsearchClient;
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.elasticsearch.client.RestClient;

import java.io.IOException;

public class ESClient {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200)).build();

        //使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());

        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(二) Java Rest Client

Java Low Level Rest Client:低级别客户端,允许通过 HTTP 请求与 ES 集群进行通信,封装度低但无视 ES 版本

Java High Level Rest Client:高级别客户端,基于低级别客户端封装

1、Java Low Level Rest Client

官网地址:

Initialization | Elasticsearch Java API Client [7.16] | Elastic

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.16.3</version>
</dependency>
public RestClient getClient() {
    // ES 连接信息
    HttpHost[] hosts = {new HttpHost("localhost", 9200, "http")};
    // 如果有密码,设置身份认证
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elasticsearch", "123456"));
    // 创建 LOW-LEVEL-CLIENT 连接
    return RestClient.builder(hosts)
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                    // 统一设置 REQUEST 请求,也可以分别设置每个 REQUEST 请求,见方法 getSpecialRequest()
                    .setConnectTimeout(6000)
                    .setSocketTimeout(6000)
            )
            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                    // 设置身份认证
                    .setDefaultCredentialsProvider(credentialsProvider)
                    // 设置线程数
                    .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(6).build())
            )
            .build();
}

/**
 * 单独设置 REQUEST 请求
 */
public Request getSpecialRequest(Request request) {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(6000)
            .setSocketTimeout(6000).build();
    RequestOptions options = RequestOptions.DEFAULT.toBuilder().setRequestConfig(requestConfig).build();
    request.setOptions(options);
    return request;
}

2、Java High Level Rest Client

官网地址:

Migrating from the High Level Rest Client | Elasticsearch Java API Client [7.16] | Elastic

// Create the low-level client
RestClientBuilder httpClientBuilder = RestClient.builder(
    new HttpHost("localhost", 9200)
);

// Create the HLRC
RestHighLevelClient hlrc = new RestHighLevelClient(httpClientBuilder);

// Create the new Java Client with the same low level client
ElasticsearchTransport transport = new RestClientTransport(
    hlrc.getLowLevelClient(),
    new JacksonJsonpMapper()
);

ElasticsearchClient esClient = new ElasticsearchClient(transport);

3、从高级客户端High Level Rest Client迁移至新版客户端Elasticsearch Java API Client

官方给出的答案是无法平滑的迁移,不过新版客户端和旧版高级客户端是可以共存的,并且没有操作开销。所以在你的项目中可以逐步的从旧版客户端迁移至新版客户端

并且,官方还提供了使High Level Rest Client和Elasticsearch Java API Client使用相同的传输通道的方案,他可以使两个客户端共享相同的Low Level Rest Client,管理所有连接,循环策略的网络层以及节点嗅探等工作。

以下代码展示了如何使用相同的HTTP客户端同时初始化新客户端和旧客户端:

// 创建低级客户端(新版客户端内容)
RestClientBuilder httpClientBuilder = RestClient.builder(
    new HttpHost("localhost", 9200)
);
 
// 创建旧版高级客户端RestHighLevelClient 
RestHighLevelClient hlrc = new RestHighLevelClient(httpClientBuilder);
 
// 使用相同的低级客户端创建新的Java客户端
ElasticsearchTransport transport = new RestClientTransport(
    hlrc.getLowLevelClient(),
    new JacksonJsonpMapper()
);
 
ElasticsearchClient esClient = new ElasticsearchClient(transport);
 
// 新旧客户端共享相同的http客户端

二、索引操作

Java 8 (又称为 jdk 1.8) 是 Java 语言开发的一个主要版本。 Oracle 公司于 2014 年 3 月 18 日发布 Java 8 ,它支持函数式编程,新的 JavaScript 引擎,新的日期 API,新的Stream API 等

Lambda 表达式 − Lambda 允许把函数作为一个方法的参数(函数作为参数传递到方法中)

本demo主要使用Lambda表达式操作

1、创建索引

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.io.IOException;

public class ESIndexCreate {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 创建索引
            CreateIndexResponse response = esClient.indices().create(c -> c.index("user"));

            // 响应状态
            boolean acknowledged = response.acknowledged();
            System.out.println("创建索引:" + acknowledged);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、查看索引

public class ESIndexSearch {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 查询索引
            GetIndexResponse response = esClient.indices().get(c -> c.index("user"));

            // 响应状态
            System.out.println("查询索引:" + String.join(",", response.result().keySet()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、删除索引

public class ESIndexDelete {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 删除索引
            DeleteIndexResponse response = esClient.indices().delete(c -> c.index("user"));

            // 响应状态
            System.out.println("删除索引:" + response.acknowledged());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、文档操作

创建User对象

public class User {
    private String name;
    private String sex;
    private Integer age;

    public User() {
    }
    
    public User(String name, String sex, Integer age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}

1、新增文档

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.CreateResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.io.IOException;

public class ESDocCreate {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 创建一个需要保存至ES的对象
            User user = new User();
            user.setName("zhangsan");
            user.setSex("男");
            user.setAge(24);

            // 创建文档
            CreateResponse response = esClient.create(c -> c.index("user").id("1001").document(user));

            // 响应状态
            System.out.println("创建文档:" + response.result());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、查询文档

public class ESDocSearch {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {

            // 查询文档
            GetResponse response = esClient.get(c -> c.index("user").id("1001"),User.class);

            // 响应状态
            System.out.println("查询文档:" + response.source().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、修改文档

public class ESDocUpdate {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 使用map集合封装需要修改的内容
            Map<String, Object> map = new HashMap<>();
            map.put("name", "lisi");

            // 修改文档
            UpdateResponse<User> response = esClient.update(c -> c.index("user").id("1001").doc(map),User.class);

            // 响应状态
            System.out.println("修改文档:" + response.result());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4、 删除文档

public class ESDocDelete {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 删除文档
            DeleteResponse response = esClient.delete(c -> c.index("user").id("1001"));

            // 响应状态
            System.out.println("删除文档:" + response.result());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5、批量新增

批量添加的核心是需要构建一个泛型为BulkOperationArrayList集合,实质上是将多个请求包装到一个集合中,进行统一请求,进行构建请求时调用bulk方法,实现批量添加效果

public class ESDocBatchCreate {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 构建一个批量数据集合
            List<BulkOperation> list = new ArrayList<>();
            list.add(new BulkOperation.Builder().create(d -> d.document(new User("zhangsan","男",18)).id("1001").index("user")).build());
            list.add(new BulkOperation.Builder().create(d -> d.document(new User("lisi","男",20)).id("1002").index("user")).build());
            list.add(new BulkOperation.Builder().create(d -> d.document(new User("lilei","女",16)).id("1003").index("user")).build());

            // 调用bulk方法执行批量插入操作
            BulkResponse response = esClient.bulk(c -> c.index("user").operations(list));

            // 响应状态
            System.out.println("批量创建文档:" + response.items());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6、批量删除

public class ESDocBatchDelete {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try {
            // 构建一个批量数据集合
            List<BulkOperation> list = new ArrayList<>();
            list.add(new BulkOperation.Builder().delete(d -> d.id("1001").index("user")).build());
            list.add(new BulkOperation.Builder().delete(d -> d.id("1002").index("user")).build());
            list.add(new BulkOperation.Builder().delete(d -> d.id("1003").index("user")).build());

            // 调用bulk方法执行批量操作
            BulkResponse response = esClient.bulk(c -> c.index("user").operations(list));

            // 响应状态
            System.out.println("批量删除文档:" + response.items());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

四、高级查询

1、全量查询

public class ESSearchAll {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 全量查询
            SearchResponse<User> searchResponse = esClient.search(e -> e.index("user").query(q -> q.matchAll(m -> m)), User.class);
            HitsMetadata<User> hits = searchResponse.hits();
            for (Hit<User> hit : hits.hits()) {
                System.out.println("user = " + hit.source().toString());
            }
            System.out.println("全量查询:" + searchResponse.hits().total().value());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、分页查询

public class ESSearchPage {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 分页查询
            SearchResponse<User> response3 = esClient.search(s -> s
                            .index("user")
                            .query(q -> q.matchAll(m -> m))
                            .from(0)
                            .size(2)
                    , User.class);
            System.out.println("分页查询:" + response3.took());
            System.out.println("分页查询:" + response3.hits().total().value());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、排序查询

public class ESSearchSort {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 排序查询
            SearchResponse<User> searchResponse = esClient.search(
                    s -> s.index("user")
                            .query(q -> q.matchAll(m -> m))
                            .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
                    , User.class);
            searchResponse.hits().hits().forEach(h -> System.out.println("排序查询:" + h.source().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4、 条件过滤查询

public class ESSearchFilter {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 条件查询
            SearchResponse<User> searchResponse = esClient.search(
                    s -> s.index("user").query(q -> q.matchAll(m -> m))
                            .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
                            .source(r -> r.filter(f -> f.includes("name", "age").excludes("")))
                    , User.class);
            searchResponse.hits().hits().forEach(h -> System.out.println("条件查询:" + h.source().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5、组合查询

public class ESSearchComb {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 组合查询
            SearchResponse<User> searchResponse = esClient.search(
                    s -> s.index("user").query(q -> q.bool(b -> b
                            .must(m -> m.match(u -> u.field("age").query(FieldValue.of(18))))
                            .must(m -> m.match(u -> u.field("sex").query(FieldValue.of("男"))))
                            .mustNot(m -> m.match(u -> u.field("sex").query(FieldValue.of("女"))))
                    ))
                    , User.class);
            searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6、范围查询

public class ESSearchRange {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 范围查询,gte()表示取大于等于,gt()表示大于,lte()表示小于等于
            SearchResponse<User> searchResponse = esClient.search(s -> s.index("user").query(q -> q
                            .range(r -> r.field("age").gte(JsonData.of(15)).lt(JsonData.of(20))))
                    , User.class);
            searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7、模糊查询

public class ESSearchFuzzy {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 模糊查询,fuzziness表示差几个可以查询出来
            SearchResponse<User> searchResponse = esClient.search(s -> s.index("user").query(q -> q
                            .fuzzy(f -> f.field("name").value(FieldValue.of("zhangsan")).fuzziness("18")))
                    , User.class);
            searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

8、高亮查询

public class ESSearchHigh {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 高亮查询
            SearchResponse<User> searchResponse = esClient.search(s -> s.index("user").query(q -> q
                            .term(t -> t.field("name").value(FieldValue.of("zhangsan"))))
                            .highlight(h -> h.fields("name", f -> f.preTags("<font color='red'>").postTags("</font>")))
                    , User.class);
            searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

9、聚合查询

public class ESSearchAggr {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 聚合查询,取最大年龄
            SearchResponse<User> searchResponse = esClient.search(s -> s.index("user").aggregations("maxAge", a ->a.max(m -> m.field("age")))
                    , User.class);
            searchResponse.aggregations().entrySet().forEach(f -> System.out.println(f.getKey() + ":" + f.getValue().max().value()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

10、分组查询

public class ESSearchGroup {
    public static void main(String[] args) {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
        // 使用Jackson映射器创建传输层
        RestClientTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
        // 创建API客户端
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

        try{
            // 分组查询
            SearchResponse<User> searchResponse = esClient.search(s -> s.index("user")
                            .aggregations("ageGroup", a ->a.terms(t -> t.field("age")))
                    , User.class);
            searchResponse.aggregations().get("ageGroup").lterms().buckets().array().forEach(f -> System.out.println(f.key() + ":" + f.docCount()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭ES客户端
        try {
            transport.close();
            restClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值