Springboot整合ElasticSearch

一.项目目录结构

1.pom文件相关的maven依赖

要注意到
elasticsearch版本要和自己下载的版本一致;
springboot使用版本为2.5.4

<?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.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.porridge</groupId>
    <artifactId>porridge-es-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>porridge-es-api</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>

        <!--自定义版本依赖-->
        <elasticsearch.version>7.13.2</elasticsearch.version>
    </properties>
    <dependencies>
        <!--json对象转换-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <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.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>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.config

config包下的ElasticsearchClientConfig

@Configuration
public class ElasticsearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }
}

3.User

实体类

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
}

4.PorridgeEsApiApplication

@SpringBootApplication
public class PorridgeEsApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(PorridgeEsApiApplication.class, args);
    }

}

二.相关API测试

在这里要先启动ElasticSearch
在测试类中进行依赖注入
在这里插入图片描述

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

1.索引

索引的创建

    @Test
    void testCreateIndex() throws IOException {
        //1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("book");
        //2.执行创建请求 IndicesClient  请求后获得响应
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }

访问localhost:9100
在这里插入图片描述
获得索引

判断是否存在

    @Test
    void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("book");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //存在返回true
        System.out.println(exists);
    }

删除索引

    @Test
    void testdelIndex() throws IOException {
        DeleteIndexRequest Request = new DeleteIndexRequest("book");
        AcknowledgedResponse delete = client.indices().delete(Request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

添加文档

    @Test
    void testAddDocument() throws IOException {
        User user = new User("porridge", 3);
        //创建请求
        IndexRequest request = new IndexRequest("book");
        //规则  put /book/_doc/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");
        //将对象转换成json
        IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);
        //客户端发送请求,获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
        System.out.println(indexResponse.status());
    }

判断文档是否存在

    @Test
    void testIsExists() throws IOException {
        GetRequest getRequest = new GetRequest("book", "1");
        //不获取返回的_source 的上下文
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);

    }

获取文档信息

    @Test
    void getDocument() throws IOException {
        GetRequest getRequest = new GetRequest("book", "1");
        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        String sourceAsString = documentFields.getSourceAsString();
        //文档内容
        System.out.println(sourceAsString);
        //获取全部信息
        System.out.println(documentFields);
    }

更新文档

    @Test
    void UpdateRequest() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("book","1");
        //超过的时间
        updateRequest.timeout("1s");
        User user = new User("李大哥2222", 18);
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.status());
    }

删除文档信息

    @Test
    void delRequest() throws IOException {
        DeleteRequest request = new DeleteRequest("book", "1");
        request.timeout("1s");
        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }

批量添加数据

    @Test
    void testBulkRequest() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList<Object> arrayList = new ArrayList<>();
        
        arrayList.add(new User("porridge",1));
        arrayList.add(new User("porridge2",2));
        arrayList.add(new User("porridge3",7));
        arrayList.add(new User("porridge4",6));
        arrayList.add(new User("porridge5",2));
        arrayList.add(new User("he",3));
        arrayList.add(new User("he3",3));

        for (int i = 0; i < arrayList.size(); i++) {
            //批量处理请求
            //批量更新、批量删除就在这里修改对应的请求
            bulkRequest.add(
                    new IndexRequest("book")
                    .id(""+(i+1))
                    .source(JSON.toJSONString(arrayList.get(i)),XContentType.JSON));
            BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            //是否失败  返回false代表成功
            System.out.println(bulk.hasFailures());
        }
    }

多条件查询

    //search  查询
    //SearchSourceBuilder 条件构造查询
    //HighlightBuilder   高亮查询
    //TermQueryBuilder  精确查询
    //MatchAllQueryBuilder  查询全部
    //xxxQueryBuilder  对应我们刚才看见的searchSourceBuilder命令
    @Test
    void search() throws IOException {
        //创建查询请求
        SearchRequest searchRequest = new SearchRequest("book");
        //构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //searchSourceBuilder.from();

        HighlightBuilder highlighter = searchSourceBuilder.highlighter();
        RangeQueryBuilder age = QueryBuilders.rangeQuery("age").gte("1").lte("3");

        //条件查询  ,可以使用QueryBuilder  工具类来实现
        //QueryBuilders.termQuery();  精确查询
        //QueryBuilders.matchAllQuery();  匹配所有类型的
        //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();

        //TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", "3");
        searchSourceBuilder.query(age);
        //设置延时
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //设置搜索资源
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(search.getHits()));
        System.out.println("==================");

        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }


    }
好的,下面是SpringBoot整合elasticsearch的步骤: 1. 引入elasticsearch和spring-boot-starter-data-elasticsearch的依赖: ``` <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.12.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> <version>2.4.5</version> </dependency> ``` 2. 配置elasticsearch连接信息: ``` spring.data.elasticsearch.cluster-nodes=localhost:9200 ``` 3. 创建实体类: ``` @Document(indexName = "my_index") public class MyEntity { @Id private String id; private String name; // getter and setter } ``` 4. 创建es的Repository: ``` public interface MyRepository extends ElasticsearchRepository<MyEntity, String> { } ``` 5. 在service中使用Repository: ``` @Service public class MyService { @Autowired private MyRepository myRepository; public void save(MyEntity entity) { myRepository.save(entity); } public List<MyEntity> search(String name) { return myRepository.findByName(name); } } ``` 6. 在controller中调用service: ``` @RestController public class MyController { @Autowired private MyService myService; @PostMapping("/save") public void save(@RequestBody MyEntity entity) { myService.save(entity); } @GetMapping("/search") public List<MyEntity> search(@RequestParam String name) { return myService.search(name); } } ``` 这样就可以通过SpringBoot整合elasticsearch实现数据的增删查了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值