尝试整合SpringBoot2.x

加载依赖

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

SpringBoot整合代码位置

springboot版本跟es对应 springboot操作es_elasticsearch


在idea中配置application.properties:

spring.elasticsearch.rest.uris=http://192.168.101.7:9200
spring.data.elasticsearch.cluster-name=docker-cluster
spring.data.elasticsearch.cluster-nodes=192.168.101.7:9300

Idea运行后报错

Version Elasticsearch Client in build: 7.6.2
Version Elasticsearch Client in build: 6.8.8

意思我是我正在使用的elasticsearch版本与springboot集成的版本不一致
Ubuntu中Docker安装7.6.2后,访问页面端口失败,容器自动关停,查看logs发现如下错误:

[1]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured

解决问题:

1)重新配置容器

docker network create elastic
docker run --name es -e EX_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 -e cluster.initial_master_nodes="es762" --net elastic elasticsearch:7.6.2

ubuntu中修改elasticsearch.yml配置文件,如果没有这条则添加

springboot版本跟es对应 springboot操作es_elasticsearch_02


docker 中重启 es 容器,尝试访问页面,成功:

springboot版本跟es对应 springboot操作es_springboot版本跟es对应_03

安装ElasticSearch-head插件

master_not_discovered_exception

错误的写法,masternodes后面没有加空格

springboot版本跟es对应 springboot操作es_spring_04


正确的写法,冒号:后面都要加空格

springboot版本跟es对应 springboot操作es_spring_05

进入es容器进行配置

这些一大堆都加了,但是还是同样的错误,为什么?
后来终于弄懂了,这个文件很可能根本就不会被我的容器作为配置文件,需要进入容器才行:

docker exec -it es /bin/bash

springboot版本跟es对应 springboot操作es_spring_06


继续cd 到 config 中

springboot版本跟es对应 springboot操作es_springboot版本跟es对应_07

尝试打开配置文件

vi elasticsearch.yml 或 vim elasticsearch.yml

如果 vim 命令not a command,则安装之

apt-get install vim 或 yum install vim

修改配置文件

进入到yml文件添加:

http.host: 0.0.0.0
cluster.name: "my-cluster"
network.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin: "*"

discovery.zen.minimum_master_nodes: 1

其中:

cluster.name: 自定义集群的名称
network.host: 当前es节点绑定的ip,默认127.0.0.1,如果需要开放对外访问这个属性必须设置
http.cors.enabled: 是否支持跨域,默认为false
http.cors.allow-origin: 当设置允许跨域时,默认为*,表示支持所有域名,如果我们只是允许某些网站的访问,那么可以使用正则表达式。

重启es容器

docker restart es容器名

访问9200页面

springboot版本跟es对应 springboot操作es_springboot版本跟es对应_08

连接es插件elasticsearch-head

springboot版本跟es对应 springboot操作es_elasticsearch_09

正式整合SpringBoot2.x

es配置文件

package com.ezerbel.elastic.config;

import lombok.extern.slf4j.Slf4j;
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;

//目前官方推荐使用restHightLevelClient
@Slf4j
@Configuration
public class ElasticsearchConfig {
    @Bean
    RestHighLevelClient restHighLevelClient(){
        HttpHost httpHost = new HttpHost("192.168.101.7",9200,"http");
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHost));
        return client;
    }
}

测试代码

package com.ezerbel.elastic;

import com.alibaba.fastjson.JSON;
import com.ezerbel.elastic.bean.Car;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@Slf4j
@SpringBootTest
class Springboot03ElasticApplicationTests {

    @Resource
    RestHighLevelClient restHighLevelClient;

    @BeforeEach
    public void testBefore(){
        System.out.println("--------------------------测试开始--------------------------");
    }

    @AfterEach
    public void testAfter(){
        System.out.println("--------------------------测试结束--------------------------");
    }


    @Test
    public void testCreateIndex() throws Exception{
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("test_index");
        CreateIndexResponse indexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse);
    }


    @Test
    public void testExistIndex() throws Exception{
        GetIndexRequest getIndexRequest = new GetIndexRequest("test_index");
        boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    @Test
    public void testDeleteIndex() throws Exception{
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test_index");
        AcknowledgedResponse response = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    @Test
    public void testAddDocument()throws  Exception{
        Car car = new Car();
        car.setName("Losless");
        car.setId(1);
        IndexRequest indexRequest = new IndexRequest("test_index");
        indexRequest.id("1001");
        //设置超时时间1秒
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        //使用fastJson转为json字符串
        indexRequest.source(JSON.toJSONString(car), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexRequest.toString());
    }

    @Test
    public void testDeleteDocument() throws Exception{
        DeleteRequest deleteRequest = new DeleteRequest("test_index", "1001");
        deleteRequest.timeout(TimeValue.timeValueSeconds(1));
        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }

    @Test
    public void testBulkRequest() throws Exception{

        //批量插入
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(1));
        for (int i = 0; i < 10; i++) {
            Car car = new Car();
            car.setId(i);
            car.setName("Losless"+i);
            bulkRequest.add(new IndexRequest("test_index")
                    .id(""+(i+1000))
                    .source(JSON.toJSONString(car),XContentType.JSON));
        }
        BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkItemResponses.hasFailures());

        System.out.println(bulkItemResponses.getItems().length);
    }

    @Test
    public void testSearchAllRequest()throws  Exception{

        SearchRequest searchRequest = new SearchRequest("warehouse");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.highlighter();

        //精确查询
        //QueryBuilders.termQuery();

        //匹配所有
        //QueryBuilders.matchAllQuery();

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "BenzG");
        MatchAllQueryBuilder allQueryBuilder = QueryBuilders.matchAllQuery();

        searchSourceBuilder.query(allQueryBuilder);
        //searchSourceBuilder.query(termQueryBuilder);

        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));

        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        searchResponse.getHits().forEach(x->{
            System.out.println(x.getSourceAsMap());
        });

    }

    @Test
    public void testSearchSpecifyRequest()throws  Exception{

        SearchRequest searchRequest = new SearchRequest("warehouse");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.highlighter();

        //如果使用name做为查询条件,查询出的结果数量始终为0,为什么,因为name不是默认的索引么?
        //在postman中是可以用name做索引查到的啊!
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("id", "1002");

        searchSourceBuilder.query(termQueryBuilder);

        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));

        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        searchResponse.getHits().forEach(x->{
            System.out.println(x.getSourceAsMap());
        });

    }
}