Elasticsearch學習<四>SpringBoot整合es

蝸牛2219發表於2020-12-10

一、Java操作es有兩種方式:

1、tcp的方式

2、http的方式

二、具體步驟:

1、建立一個springboot專案

2、開啟官方文件:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.x/java-rest-high.html

3、安裝文件操作

3.1、新增maven依賴:

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

因為springbotot中有es的依賴版本號,這塊我們改一下和我們自己的一致:進行這四步操作

3.2、新增操作客戶端

@Configuration
public class ElasticSearchConfig {

    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("ip", 9200, "http")));
//ip地址,埠號,互動方式
        return client;
    }
}

4、新增

   public void save() throws IOException {
        IndexRequest request = new IndexRequest("users");
        request.id("1");
        User user = new User();
        user.setAge(2);
        user.setName("我是中國人");
        user.setSex("男");

        request.source(new ObjectMapper().writeValueAsString(user), XContentType.JSON);
        IndexResponse index = client.index(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
        System.out.println(index);
    }

5、查詢

 public void searchSyn() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("users");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(searchResponse.toString());

    }

複雜操作可以安裝官網上的例子進行操作。

相關文章