springboot使用es入门(6.3.2版本)

110 篇文章 1 订阅
3 篇文章 0 订阅

使用前先对照springboot和es和spring-data之间的版本关系

https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions
在这里插入图片描述

springboot使用es

es有两个端口可以用9200和9300(TCP端口后期es官方弃用),这里整合就使用9200了。

这里工具类采用es官方提供的.使用Java High Level REST Client
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.3.2</version>
</dependency>

在这里插入图片描述

es的启动类配置
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));

在这里插入图片描述

配置java bean

package com.fchan.espractice.config;


import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

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

        return client;
    }


}

增删改查demo

package com.fchan.espractice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fchan.espractice.pojo.User;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@SpringBootTest
class EsPracticeApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ObjectMapper objectMapper;


    //测试创建索引
    @Test
    public void testCreateIndex() throws IOException {
        //创建索引请求
        CreateIndexRequest indexRequest = new CreateIndexRequest("fchan_test");
        //执行创建请求 IndicesClient
        Header header = new BasicHeader("Content-Type", "application/json");
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(indexRequest, header);

        System.out.println(objectMapper.writeValueAsString(createIndexResponse));

    }

    //测试索引是否存在
    @Test
    public void testExistindex() throws IOException {
        GetIndexRequest request = new GetIndexRequest();
        request.indices("fchan_test");

        //执行创建请求 IndicesClient
        Header header = new BasicHeader("Content-Type", "application/json");
        boolean exists = restHighLevelClient.indices().exists(request, header);


        System.out.println(exists);
    }

    //测试删除索引
    @Test
    public void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("fchan_test");
        //执行创建请求 IndicesClient
        Header header = new BasicHeader("Content-Type", "application/json");
        DeleteIndexResponse delete = restHighLevelClient.indices().delete(request, header);

        System.out.println(objectMapper.writeValueAsString(delete));


    }

    //测试添加文档
    @Test
    public void testAddDocument() throws JsonProcessingException {
        User user = new User("张11", 3, "aaa");
        //请求要操作的索引库
        IndexRequest request = new IndexRequest("fchan_test");

        //设置请求的规则  put /fchan_test/_doc/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.type("user_2");

        //将数据放入请求
        request.source(objectMapper.writeValueAsString(user), XContentType.JSON);

        try {
            //发送请求获取响应结果
            Header header = new BasicHeader("Content-Type", "application/json");
            IndexResponse index = restHighLevelClient.index(request, header);
            System.out.println(objectMapper.writeValueAsString(index));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    //查询文档是否存在
    @Test
    public void testGetIndex() throws IOException {
        GetRequest request = new GetRequest("fchan_test", "user", "1");
        //是否返回 _source
        request.fetchSourceContext(new FetchSourceContext(false));
        //可以指定返回的字段, 即 select xx,xx,xx from xx_table
        //request.storedFields("_none_");

        Header header = new BasicHeader("Content-Type", "application/json");
        boolean exists = restHighLevelClient.exists(request, header);

        System.out.println(exists);

    }


    //查询文档
    @Test
    public void testQueryDocument() throws IOException {
        GetRequest request = new GetRequest("fchan_test", "user", "1");

        Header header = new BasicHeader("Content-Type", "application/json");
        GetResponse documentFields = restHighLevelClient.get(request, header);

        System.out.println(objectMapper.writeValueAsString(documentFields));


    }


    //更新文档
    @Test
    public void testUpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("fchan_test", "user", "1");
        request.timeout("1s");

        User user = new User("张3333", 33, "11");
        request.doc(objectMapper.writeValueAsString(user), XContentType.JSON);

        Header header = new BasicHeader("Content-Type", "application/json");
        UpdateResponse update = restHighLevelClient.update(request, header);

        System.out.println(objectMapper.writeValueAsString(update));


    }


    //删除文档
    @Test
    public void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("fchan_test", "user", "1");
        request.timeout(TimeValue.timeValueMillis(1));

        Header header = new BasicHeader("Content-Type", "application/json");
        DeleteResponse delete = restHighLevelClient.delete(request, header);

        System.out.println(objectMapper.writeValueAsString(delete));
    }


    //批量新增
    @Test
    public void testBatchAddDocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (int i = 0; i < 10; i++) {
            //如果存在id一样的数据,那么此次批量新增的时候会冲掉之前的数据,新增的时候有些字段没给值,那么会将这些字段的值冲掉->null
            IndexRequest request = new IndexRequest("fchan_test", "user");
            //这里不给id的话,es会自己给一个随机id
            request.id("" + (i + 1));
            request.source(objectMapper.writeValueAsString(new User("陈" + (i + 1), i + 1)), XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, new BasicHeader("Content-Type", "application/json"));
        //是否失败 false代表成功,因为这个方法是 hasFailures 就是问有没有失败的,没有失败的那就是false啊
        System.out.println(bulk.hasFailures());
        //全部的返回结果
        System.out.println(objectMapper.writeValueAsString(bulk));
    }


    //带条件查询
    @Test
    public void testQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("fchan_test");
        //构建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //高亮
        //searchSourceBuilder.highlighter()

        //精确匹配
        //TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张5");
        //通配符查询,效率比较低
        WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery("name.keyword", "*张5*");
        //匹配所有
        //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        //searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.query(wildcardQuery);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(searchSourceBuilder);

        Header header = new BasicHeader("Content-Type", "application/json");
        SearchResponse search = restHighLevelClient.search(searchRequest, header);
        System.out.println(objectMapper.writeValueAsString(search));
        System.out.println("======================================");
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }


    }


    //批量删除,这里采用先查询出id,再批量删除
    @Test
    public void testBatchDeleteDocument() throws IOException {

        SearchRequest searchRequest = new SearchRequest("fchan_test");
        searchRequest.types("user");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.timeout(TimeValue.MINUS_ONE);

        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
        searchSourceBuilder.query(matchQueryBuilder);

        searchRequest.source(searchSourceBuilder);

        Header header = new BasicHeader("Content-Type", "application/json");
        SearchResponse search = restHighLevelClient.search(searchRequest, header);


        BulkRequest bulkRequest = new BulkRequest();
        for (SearchHit hit : search.getHits().getHits()) {
            DeleteRequest request = new DeleteRequest("fchan_test");
            request.type("user");
            request.id(hit.getId());
            bulkRequest.add(request);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, header);
        System.out.println(objectMapper.writeValueAsString(bulk));
    }


}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中集成带有用户名密码的Elasticsearch 6.3.2版本,你可以按照以下步骤进行操作: 1. 首先,将Elasticsearch 6.3.2版本的依赖项添加到你的Spring Boot项目的pom.xml文件中: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 在application.properties(或application.yml)文件中配置Elasticsearch连接属性和身份验证信息。示例配置如下: ```properties spring.data.elasticsearch.cluster-nodes=localhost:9300 spring.data.elasticsearch.cluster-name=my-cluster spring.data.elasticsearch.properties.transport.tcp.port=9300 spring.data.elasticsearch.properties.transport.tcp.compress=true spring.data.elasticsearch.properties.transport.tcp.connect_timeout=5s spring.data.elasticsearch.properties.transport.tcp.socket_timeout=5s spring.data.elasticsearch.properties.transport.tcp.keep_alive=true spring.data.elasticsearch.properties.transport.tcp.no_delay=true spring.data.elasticsearch.properties.transport.tcp.send_buffer_size=1mb spring.data.elasticsearch.properties.transport.tcp.receive_buffer_size=1mb spring.data.elasticsearch.properties.transport.tcp.keep_alive_interval=30s # 身份验证相关配置 spring.data.elasticsearch.properties.transport.tcp.username=my-username spring.data.elasticsearch.properties.transport.tcp.password=my-password ``` 3. 创建一个Elasticsearch配置类,用于创建Elasticsearch客户端的bean,并设置身份验证信息。示例代码如下: ```java import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; @Configuration @EnableElasticsearchRepositories(basePackages = "com.example.repository") public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { @Value("${spring.data.elasticsearch.cluster-nodes}") private String clusterNodes; @Value("${spring.data.elasticsearch.cluster-name}") private String clusterName; @Value("${spring.data.elasticsearch.properties.transport.tcp.username}") private String username; @Value("${spring.data.elasticsearch.properties.transport.tcp.password}") private String password; @Override public RestHighLevelClient elasticsearchClient() { final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo(clusterNodes) .withBasicAuth(username, password) .build(); return RestClients.create(clientConfiguration).rest(); } } ``` 在上面的示例中,我们使用了`RestHighLevelClient`来创建一个Elasticsearch客户端,并设置了身份验证信息。 4. 创建一个Elasticsearch存储库接口,用于定义与Elasticsearch的交互操作。示例代码如下: ```java import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; @Repository public interface MyElasticsearchRepository extends ElasticsearchRepository<YourEntity, String> { // 自定义查询方法 } ``` 请将`YourEntity`替换为你的实体类。 现在,你已经完成了Spring Boot与带有用户名密码的Elasticsearch 6.3.2版本的集成。你可以使用自动注入的Elasticsearch存储库接口来执行与Elasticsearch的数据交互操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值