Springboot集成ElasticSearch

Posted Zeran

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot集成ElasticSearch相关的知识,希望对你有一定的参考价值。

Springboot项目集成ElasticSearch7.6.1

pom依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>7.6.1</version>
        </dependency>

2.配置ip

@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost("你的esip", 端口, "http")));
    }
}

3.创建User实体

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class User {
    /**
     * 名称
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;

}

4.创建测试类EsApiApplicationTests,并注入EslasticSearch客户端的bean

@SpringBootTest
class EsApiApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    RestHighLevelClient client;
}
创建一个索引
/**
     * 创建索引
     */
    @Test
    public void createIndex() throws IOException {
        // 创建索引
        CreateIndexRequest index = new CreateIndexRequest("yzr_index");
        // 执行请求
        CreateIndexResponse createIndexResponse = client.indices().create(index, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
获取一个索引,并判断是否存在
/**
     * 获取索引,判断是否存在
     *
     * @throws IOException
     */
    @Test
    public void getIndex() throws IOException {
        // 获取索引请求
        GetIndexRequest indexRequest = new GetIndexRequest("yzr_index");
        // 执行请求
        boolean exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
删除一个索引
/**
     * 删除索引
     *
     * @throws IOException
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("yzr_index");
        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }
添加一个文档
/**
     * 添加文档
     */
    @Test
    public void createDocumentation() throws IOException {
        User user = User
                .builder()
                .name("yzr")
                .age(20)
                .build();
        // 创建请求
        IndexRequest request = new IndexRequest("yzr_index");

        // 规则 PUT /yzr_index/1
        request.id("1");
        request.timeout("1s");

        // 对象转json
        request.source(JSON.toJSONString(user), XContentType.JSON);

        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        System.out.println(index.toString());
        System.out.println(index.status());
    }
获取文档
/**
     * 获取
     *
     * @throws IOException
     */
    @Test
    public void queryDocumentation() throws IOException {
        GetRequest request = new GetRequest("yzr_index", "1");
        GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);

        System.out.println(documentFields.getSourceAsString());
        System.out.println(documentFields);
    }
更新一个文档
/**
     * 更新文档
     *
     * @throws IOException
     */
    @Test
    public void updateDocumentation() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("yzr_index", "1");
        updateRequest.timeout(TimeValue.MINUS_ONE);
        User build = User.builder()
                .name("杨泽然")
                .age(20)
                .build();
        updateRequest.doc(JSON.toJSONString(build), XContentType.JSON);
        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.status());
    }
删除一个文档
@Test
    public void deleteDocumentation() throws IOException {
        DeleteRequest request = new DeleteRequest("yzr_index", "1");

        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }
批量添加文档
@Test
    public void bulkDocumentation() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();

        List<User> userList = new ArrayList<>();
        userList.add(User.builder().name("11").age(20).build());
        userList.add(User.builder().name("22").age(21).build());
        userList.add(User.builder().name("33").age(22).build());
        userList.add(User.builder().name("44").age(23).build());
        userList.add(User.builder().name("55").age(25).build());
        userList.add(User.builder().name("66").age(26).build());
        userList.add(User.builder().name("77").age(22).build());

        for (int i = 0; i < userList.size(); i++) {
            bulkRequest.add(new IndexRequest("yzr_index").id("" + i + 1).source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());
        System.out.println(bulk);
    }
条件查询
@Test
    public void search() throws IOException {
        SearchRequest request = new SearchRequest("yzr_index");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 构建条件
        // 精确查询
        // QueryBuilders.matchQuery("name", "杨泽然");
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "杨泽然3");

        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(searchSourceBuilder);

        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(search.getHits()));
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

官网文档地址:https://www.elastic.co/guide/...

以上是关于Springboot集成ElasticSearch的主要内容,如果未能解决你的问题,请参考以下文章

精通系列SpringBoot集成ElasticSearch+项目实战

精通系列SpringBoot集成ElasticSearch+项目实战

精通系列SpringBoot集成ElasticSearch+项目实战

springboot集成ElasticSearch

springboot集成elk 三:springboot + Elasticsearch Rest-Client

springboot集成elasticsearch全文搜索高亮显示实践