springboot整合elasticsearch

点击查看官方文档

1、导入pom

<?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.1.8.RELEASE</version>
        <!-- lookup parent from repository ,MAVEN构建jar包时候查找顺序:relativePath元素中的地址–本地仓库–远程仓库 -->
        <relativePath/>
    </parent>

    <groupId>com.lian.gulimall</groupId>
    <artifactId>gulimall-search</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gulimall-search</name>
    <description>检索服务</description>
    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.4.2</elasticsearch.version>
    </properties>

    <dependencies>
        <!--导入高阶es的client-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.2</version>
        </dependency>
        <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
        <dependency>
            <groupId>com.lian.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、配置类

package com.lian.gulimall.search.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 ElasticSearchClientConfig {

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

3、主启动类

package com.lian.gulimall.search;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

//开启nacos服务注册与发现
@EnableDiscoveryClient
//排除数据源
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class GulimallSearchApplication {

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

}

4、测试类

rest client 官方文档

kibana查询数据

GET /test1/_search
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "ageAggs": {
      "terms": {
        "field": "age",
        "size": 10
      },
      "aggs": {
        "sexAggs": {
          "terms": {
            "field": "sex.keyword",
            "size": 10
          },
          "aggs": {
            "balanceAvg": {
              "avg": {
                "field": "salary"
              }
            }
          }
        }
      }
    }
  },
  "size": 0
}

实操增删改查

/**
 * 注解的意义在于Test测试类要使用注入的类,比如@Autowired注入的类,
 * 有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效,
 * 不然直接一个NullPointerExecption
 */
@RunWith(SpringRunner.class)
@SpringBootTest
class EsApplicationTests {

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

	//创建索引
	@Test
	void createIndex() throws IOException {

		//1、创建索引请求
		CreateIndexRequest request = new CreateIndexRequest("pi_index");
		//2、执行请求,获得响应
		CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
		System.out.println(response);
	}

	//判断索引是否存在
	@Test
	void existIndex() throws IOException {
		GetIndexRequest request = new GetIndexRequest("pi_index");
		boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
		System.out.println(exists);
	}

	//删除索引
	@Test
	void deleteIndex() throws IOException {
		DeleteIndexRequest request = new DeleteIndexRequest("pi_index");
		AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
		System.out.println(delete.isAcknowledged());
	}

	//添加文档
	@Test
	void addDoc() throws IOException {
		//创建对象
		User user = new User("皮", 2);
		//创建请求
		IndexRequest request = new IndexRequest("pi_index");
		//设置规则
		request.id("1");
		request.timeout(TimeValue.timeValueSeconds(1));
		request.timeout("1s");
		//将我们的数据放入请求 json,引入阿里的fastjson
		request.source(JSON.toJSONString(user), XContentType.JSON);
		//客户端发送请求,获取响应结果
		IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
		System.out.println(indexResponse.toString());
		//对应命令返回的状态 CREATED
		System.out.println(indexResponse.status());
	}

	//判断文档是否存在
	@Test
	void existDoc() throws IOException {
		//1、判断索引是否存在
		GetRequest request = new GetRequest("pi_index", "1");
		//不获取返回的上下文了
		request.fetchSourceContext(new FetchSourceContext(false));
		request.storedFields("_none_");
		boolean exists = client.exists(request, RequestOptions.DEFAULT);
		System.out.println(exists);
	}

	//获取文档的信息
	@Test
	void getDoc() throws IOException {
		//1、判断索引是否存在
		GetRequest request = new GetRequest("pi_index", "1");
		GetResponse response = client.get(request, RequestOptions.DEFAULT);
		//打印文档的内容
		System.out.println(response.getSourceAsString());
		System.out.println(response);
	}

	//更新文档的信息
	@Test
	void updateDoc() throws IOException {
		//1、创建更新请求
		UpdateRequest request = new UpdateRequest("pi_index", "1");
		request.timeout("1s");
		User user = new User("蛋蛋", 3);
		request.doc(JSON.toJSONString(user),XContentType.JSON);
		UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
		//打印文档的内容
		System.out.println(response.status());
	}

	//删除文档的信息
	@Test
	void deleteDoc() throws IOException {
		//1、创建更新请求
		DeleteRequest request = new DeleteRequest("pi_index", "1");
		request.timeout("1s");
		DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
		//打印文档的内容
		System.out.println(delete.status());
	}

	//批量插入数据
	@Test
	void Bulk() throws IOException {
		//1、创建更新请求
		BulkRequest request = new BulkRequest();
		request.timeout("1s");
		ArrayList<User> users = new ArrayList<>();
		users.add(new User("zhangsan",2));
		users.add(new User("lisi",3));
		users.add(new User("wangwu",4));
		for (int i = 0; i < users.size(); i++) {
			request.add(new IndexRequest("pi_index")
					.id(""+i)
					.source(JSON.toJSONString(users.get(i)),XContentType.JSON));
		}
		BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
		//打印文档的内容
		System.out.println(bulk.hasFailures());
	}


	//查询数据
	@Test
	void search() throws IOException {
		SearchRequest request = new SearchRequest("pi_index");
		//构建搜索条件
		SearchSourceBuilder builder = new SearchSourceBuilder();
		TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "lisi");
		builder.query(termQueryBuilder);
		request.source(builder);
		SearchResponse response = client.search(request, RequestOptions.DEFAULT);
		System.out.println(JSON.toJSONString(response.getHits()));
		for (SearchHit hit : response.getHits().getHits()) {
			System.out.println(hit.getSourceAsMap());
		}
	}
}

复杂查询

package com.lian.gulimall.search;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lian.gulimall.search.config.ElasticSearchClientConfig;
import com.lian.gulimall.search.config.pojo.User;
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.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {

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

    /**
     * 创建索引
     */
    @Test
    public void createIndex() throws IOException {

    }

    /**
     * 创建索引且将数据存储到索引
     */
    @Test
    public void contextLoads() throws IOException {
        //设置索引
        IndexRequest request = new IndexRequest("lian_index");
        //设置文档id,类型已经被淘汰了
        request.id("1");
        //将对象转为json格式
        User user = new User("zhangsan","male",3);
        //索引中封装数据
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //发送请求
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

    /**
     * 查询请求 _search
     * search api
     * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html
     */
    @Test
    public void SearchRequest() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("lian_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(searchSourceBuilder);
        //执行检索
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //分析响应
        System.out.println(response.status());
        System.out.println(response.toString());
    }

    /**
     * 查询聚合请求
     */
    @Test
    public void SearchAggrRequest() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("test1");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //按照年龄值分布聚合
        TermsAggregationBuilder aggregation = AggregationBuilders
                .terms("ageAggs").field("age").size(10);
        searchSourceBuilder.aggregation(aggregation);

        //计算平均薪资
        AvgAggregationBuilder avgAggregationBuilder = AggregationBuilders.avg("balanceAvg").field("salary");
        searchSourceBuilder.aggregation(avgAggregationBuilder);

        request.source(searchSourceBuilder);
        //执行检索
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //结果分析
        System.out.println(response.toString());
        //将解析好的json字符串转换为对象
        JSONObject object = JSON.parseObject(response.toString());
        System.out.println(object);
        //获取所有查到的数据
        SearchHits hits = response.getHits();
        SearchHit[] hitsHits = hits.getHits();
        for (SearchHit hit : hitsHits) {
            //json字符串
            String sourceAsString = hit.getSourceAsString();
            JSON.parseObject(sourceAsString);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值