elasticsearch 7.17.3下载地址:
链接:https://pan.baidu.com/s/1o30iawcZPhV6sYcd9jym9g?pwd=0nt0
提取码:0nt0

前提:需要安装elasticsearch工具

一、创建项目

1.创建个空项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
默认的(Developer Tools)都需要勾选,最主要的是NoSQL中选中ElasticSearch
配置编译版本
在这里插入图片描述
在这里插入图片描述

二、修改配置

1. 删除maven没用的插件

在这里插入图片描述

2. 修改spring版本到本地版本

在这里插入图片描述

3.修改ElasticSearch版本依赖

<elasticsearch.version>7.17.3</elasticsearch.version>
在这里插入图片描述

4.添加依赖包 (也适用Elasticsearch8.0的版本)

 		<dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.3</version>
        </dependency>

最终的pom文件如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>es-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>es-api</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>jakarta.json</groupId>
            <artifactId>jakarta.json-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.12.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                    <image>
                        <builder>paketobuildpacks/builder:tiny</builder>
                        <env>
                            <BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
                        </env>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <profiles>
        <profile>
            <id>native</id>
            <properties>
                <repackage.classifier>exec</repackage.classifier>
                <native-buildtools.version>0.9.11</native-buildtools.version>
            </properties>

        </profile>
    </profiles>

</project>

5.添加公共的链接

启动类层新建common包
在这里插入图片描述
新增链接类及返回类

package com.example.esapi.common;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.ElasticsearchTransport;
import lombok.Data;
import org.elasticsearch.client.RestClient;

@Data
public class ElasticSearchResult {

    private RestClient restClient;

    private ElasticsearchTransport elasticsearchTransport;

    private ElasticsearchClient elasticsearchClient;

    public ElasticSearchResult(RestClient restClient, ElasticsearchTransport elasticsearchTransport, ElasticsearchClient elasticsearchClient) {
        this.restClient = restClient;
        this.elasticsearchTransport = elasticsearchTransport;
        this.elasticsearchClient = elasticsearchClient;
    }
}
package com.example.esapi.common;

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 org.springframework.stereotype.Component;

@Component
public class ElasticSearchClientConnect {

    public ElasticSearchResult restClient(){
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200,"http")).build();
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);

        ElasticSearchResult elasticSearchResult=new ElasticSearchResult(restClient,transport,client);
        return elasticSearchResult;
    }

}

自此springboot集成elasticSearch已经完成,下边是应用操作。

三、elasticSearch的api应用测试(以上算是集成完成,下边是常规操作,亲测跑通)

新建User对象

package com.example.esapi.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

应用实例

package com.example.esapi.controller;

import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.json.JsonData;
import com.example.esapi.common.ElasticSearchClientConnect;
import com.example.esapi.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class Testcontroller {

    @Autowired
    private ElasticSearchClientConnect elasticSearchClientConfig;

    /**
     * 新建jing_index索引
     * @return
     * @throws IOException
     */
    @GetMapping("/getConnect")
    public Boolean withdrawQueue() throws IOException {

        CreateIndexResponse createIndexResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().indices().create(c -> c.index("jing_index"));
        // 打印结果
        System.out.println(createIndexResponse.acknowledged());
        // 关闭连接

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
        return createIndexResponse.acknowledged();
    }

    /**
     * 查询索引
     * @throws IOException
     */
    @GetMapping("/select")
    public void select() throws IOException {

        GetIndexResponse getIndexResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().indices().get(e -> e.index("jing_index"));

        // 打印结果
        System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
        System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());

        // 关闭连接
        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 删除索引
     * @return
     * @throws IOException
     */
    @GetMapping("/delete")
    public Boolean delete() throws IOException {
        // 删除索引
        DeleteIndexResponse deleteIndexResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().indices().delete(e -> e.index("jing_index"));
        System.out.println("删除操作 = " + deleteIndexResponse.acknowledged());
        // 关闭连接
        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
        return deleteIndexResponse.acknowledged();
    }

    /**
     * 添加document
     * @throws IOException
     */
    @GetMapping("/addDocument")
    public void addDocument() throws IOException {

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

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 查询document
     * @throws IOException
     */
    @GetMapping("/queryDocument")
    public void queryDocument() throws IOException {
        // 构建请求
        GetResponse<User> getResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().get(e -> e.index("jing_index").id("1001"), User.class);
        System.out.println("getResponse.source().toString() = " + getResponse.source().toString());

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 修改document
     * @throws IOException
     */
    @GetMapping("/modifyDocument")
    public void modifyDocument() throws IOException {

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

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 删除document
     * @throws IOException
     */
    @GetMapping("/removeDocument")
    public void removeDocument() throws  IOException {

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

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 批量添加document
     * @throws IOException
     */
    @GetMapping("/batchAddDocument")
    public void batchAddDocument() throws IOException {

        // 构建一个批量数据集合
        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 = elasticSearchClientConfig.restClient().getElasticsearchClient().bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 批量删除document
     * @throws IOException
     */
    @GetMapping("/batchDeleteDocument")
    public void batchDeleteDocument() throws IOException {

        // 构建一个批量数据集合
        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 = elasticSearchClientConfig.restClient().getElasticsearchClient().bulk(e -> e.index("user_test").operations(list));
        System.out.println("bulkResponse.items() = " + bulkResponse.items());

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 全量查询document
     * @throws IOException
     */
    @GetMapping("/queryAllDocument")
    public void queryAllDocument() throws IOException {

        // 全量查询
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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());

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 分页查询document
     * @throws IOException
     */
    @GetMapping("/pagingQueryDocument")
    public void pagingQueryDocument() throws IOException {

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

    /**
     * 排序查询document
     * @throws IOException
     */
    @GetMapping("/sortQueryDocument")
    public void sortQueryDocument() throws IOException {

        // 排序查询
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 条件查询document
     * @throws IOException
     */
    @GetMapping("/conditionQueryDocument")
    public void conditionQueryDocument() throws IOException {

        // 条件查询
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 组合查询  must是必须满足所有条件,should只要满足一个就行
     * @throws IOException
     */
    @GetMapping("/combinationQueryDocument")
    public void combinationQueryDocument() throws IOException {

        // 组合查询
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 范围查询
     * @throws IOException
     */
    @GetMapping("/scopeQueryDocument2")
    public void scopeQueryDocument2() throws IOException {

        // 范围查询,gte()表示取大于等于,gt()表示大于,lte()表示小于等于
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }


    /**
     * 模糊查询
     * @throws IOException
     */
    @GetMapping("/fuzzyQueryDocument2")
    public void fuzzyQueryDocument2() throws IOException {

        // 模糊查询,fuzziness表示差几个可以查询出来
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 高亮查询
     * @throws IOException
     */
    @GetMapping("/highlightQueryDocument2")
    public void highlightQueryDocument2() throws IOException {

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

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }


    /**
     * 聚合查询
     * @throws IOException
     */
    @GetMapping("/aggregateQueryDocument2")
    public void aggregateQueryDocument2() throws IOException {

        // 聚合查询,取最大年龄
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }

    /**
     * 分组查询
     * @throws IOException
     */
    @GetMapping("/groupQueryDocument2")
    public void groupQueryDocument2() throws IOException {

        // 分组查询
        SearchResponse<User> searchResponse = elasticSearchClientConfig.restClient().getElasticsearchClient().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()));

        elasticSearchClientConfig.restClient().getElasticsearchTransport().close();
        elasticSearchClientConfig.restClient().getRestClient().close();
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐