https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html

https://www.jianshu.com/p/7d55b6db8aa2

添加maven依赖:

<dependency>
      <groupId>co.elastic.clients</groupId>
      <artifactId>elasticsearch-java</artifactId>
      <version>8.4.3</version>
    </dependency>

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

如果你报了 ClassNotFoundException: jakarta.json.spi.JsonProvider异常

It may happen that after setting up the dependencies, your application fails with ClassNotFoundException: jakarta.json.spi.JsonProvider.

你需要添加 jakarta.json:jakarta.json-api:2.0.1 依赖.

<dependency>
      <groupId>jakarta.json</groupId>
      <artifactId>jakarta.json-api</artifactId>
      <version>2.0.1</version>
    </dependency>
<dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.json</artifactId>
            <version>2.0.1</version>
        </dependency>

 

创建Elasticsearch客户端

// Create the low-level client
// 创建低级客户端
RestClient restClient = RestClient.builder(
    new HttpHost("localhost", 9200)).build();

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

// And create the API client
// 创建API客户端
ElasticsearchClient client = new ElasticsearchClient(transport);

关闭客户端 

// 关闭ES客户端
        transport.close();
        restClient.close();

实现javaclient-api和RestHightLevel共存 

// 这样可以新的javaclient-api和 旧的RestHighLevel 共存

// 创建旧版高级客户端RestHighLevelClient 
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClient);

 

索引index的基本语法

创建索引

@Test
    public void create() throws IOException {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)
        ).build();
        // 使用Jackson映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );
        // 创建API客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 创建索引
        CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));
        // 响应状态
        Boolean acknowledged = createIndexResponse.acknowledged();
        System.out.println("索引操作 = " + acknowledged);

        // 关闭ES客户端
        transport.close();
        restClient.close();
    }

查询索引

@Test
    public void query() throws IOException {
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost",9200)
        ).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 查询索引
        GetIndexResponse getIndexResponse = client.indices().get(e -> e.index("user_test"));
        System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
        System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());

        transport.close();
        restClient.close();
    }

删除索引

@Test
    public void delete() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 删除索引
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index("user_test"));
        System.out.println("删除操作 = " + deleteIndexResponse.acknowledged());

        transport.close();
        restClient.close();
    }

 

文档document的操作

创建User对象

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private String sex;
    private Integer age;
}

添加document

@Test
    public void addDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 向user对象中添加数据
        User user = new User("java客户端", "男", 18);
        // 向索引中添加数据
        CreateResponse createResponse = client.create(e -> e.index("user_test").id("1001").document(user));
        System.out.println("createResponse.result() = " + createResponse.result());

        transport.close();
        restClient.close();
    }

查询document

@Test
    public void queryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建请求
        GetResponse<User> getResponse = client.get(e -> e.index("user_test").id("1001"), User.class);
        System.out.println("getResponse.source().toString() = " + getResponse.source().toString());

        transport.close();
        restClient.close();
    }


修改document

@Test
    public void modifyDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 使用map集合封装需要修改的内容
        Map<String, Object> map = new HashMap<>();
        map.put("name", "java客户端aaa");
        // 构建请求
        UpdateResponse<User> updateResponse = client.update(e -> e.index("user_test").id("1001").doc(map), User.class);
        System.out.println("updateResponse.result() = " + updateResponse.result());

        transport.close();
        restClient.close();
    }

删除document

@Test
    public void removeDocument() throws  IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建请求
        DeleteResponse deleteResponse = client.delete(e -> e.index("user_test").id("1001"));
        System.out.println("deleteResponse.result() = " + deleteResponse.result());

        transport.close();
        restClient.close();
    }

批量添加document

@Test
    public void batchAddDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建一个批量数据集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());
        list.add(new BulkOperation.Builder().create(
                d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());
        // 调用bulk方法执行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }


批量删除

@Test
    public void batchDeleteDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 构建一个批量数据集合
        List<BulkOperation> list = new ArrayList<>();
        list.add(new BulkOperation.Builder().delete(
                d -> d.id("1002").index("user_test")).build());
        list.add(new BulkOperation.Builder().delete(
                d -> d.id("1003").index("user_test")).build());
        // 调用bulk方法执行批量插入操作
        BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        transport.close();
        restClient.close();
    }

全量查询

@Test
    public void queryAllDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 全量查询
        SearchResponse<User> searchResponse = client.search(e -> e.index("user_test").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() = " + searchResponse.hits().total().value());

        transport.close();
        restClient.close();
    }

分页查询

@Test
    public void pagingQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 分页查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test")
                        .query(q -> q.matchAll(m -> m))
                        .from(2)
                        .size(2)
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }


排序查询

@Test
    public void sortQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 排序查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test")
                        .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()));

        transport.close();
        restClient.close();
    }

条件查询

@Test
    public void conditionQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 条件查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").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()));

        transport.close();
        restClient.close();
    }


组合查询

@Test
    public void combinationQueryDocument() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 组合查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.bool(b -> b
                        .must(m -> m.match(u -> u.field("age").query(21)))
                        .must(m -> m.match(u -> u.field("sex").query("男")))
                        .mustNot(m -> m.match(u -> u.field("sex").query("女")))
                ))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }
@Test
    public void combinationQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 组合查询
        SearchResponse<User> searchResponse = client.search(
                s -> s.index("user_test").query(q -> q.bool(b -> b
                        .should(h -> h.match(u -> u.field("age").query(19)))
                        .should(h -> h.match(u -> u.field("sex").query("男")))
                ))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

must是必须满足所有条件,should只要满足一个就行

范围查询

@Test
    public void scopeQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 范围查询,gte()表示取大于等于,gt()表示大于,lte()表示小于等于
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
                        .range(r -> r.field("age").gte(JsonData.of(20)).lt(JsonData.of(21))))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

模糊查询

@Test
    public void fuzzyQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 模糊查询,fuzziness表示差几个可以查询出来
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
                        .fuzzy(f -> f.field("name").value("tst").fuzziness("2")))
                , User.class);
        searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));

        transport.close();
        restClient.close();
    }

高亮查询

@Test
    public void highlightQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 高亮查询
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
                        .term(t -> t.field("name").value("test3")))
                        .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()));

        transport.close();
        restClient.close();
    }

聚合查询

@Test
    public void aggregateQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 聚合查询,取最大年龄
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").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()));

        transport.close();
        restClient.close();
    }

分组查询

@Test
    public void groupQueryDocument2() throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 分组查询
        SearchResponse<User> searchResponse = client.search(s -> s.index("user_test")
                        .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()));

        transport.close();
        restClient.close();
    }