SpringBoot与ElasticSearch整合

SpringBoot与ElasticSearch整合



<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.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.3.3.RELEASEversion>
		<relativePath/> 
	parent>
	<groupId>com.blugroupId>
	<artifactId>BLUesartifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>BLUesname>
	<description>Demo project for Spring Bootdescription>

	<properties>
		<java.version>1.8java.version>
		<elasticsearch.version>7.7.1elasticsearch.version>
	properties>

	<dependencies>
		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>fastjsonartifactId>
			<version>1.2.62version>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-elasticsearchartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-devtoolsartifactId>
			<scope>runtimescope>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-configuration-processorartifactId>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintagegroupId>
					<artifactId>junit-vintage-engineartifactId>
				exclusion>
			exclusions>
		dependency>
	dependencies>

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

project>
  • 创建配置类:
package com.blu.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("localhost",9200,"http")));
		return client;
	}
}

测试:

package com.blu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.apache.lucene.util.QueryBuilder;
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.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.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
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.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import com.alibaba.fastjson.JSON;
import com.blu.entity.User;

@SpringBootTest
class BlUesApplicationTests {
	
	@Autowired
	@Qualifier("restHighLevelClient")
	private RestHighLevelClient client;

	/**
	 * 测试创建索引
	 * @throws IOException
	 */
	@Test
	void testCreateIndex() throws IOException {
		//创建索引请求
		CreateIndexRequest request = new CreateIndexRequest("blu_index");
		//执行创建请求
		CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
		System.out.println(createIndexResponse);
		
	}
	
	/**
	 * 判断是否存在某个Index
	 * @throws IOException
	 */
	@Test
	void testExistIndex() throws IOException {
		GetIndexRequest request = new GetIndexRequest("blu_index");
		boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);
		System.out.println(exists);
	}
	
	/**
	 * 删除某个索引
	 * @throws IOException
	 */
	
	@Test
	void testDeleteIndex() throws IOException {
		DeleteIndexRequest request = new DeleteIndexRequest("blu_index");
		AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
		System.out.println(delete.isAcknowledged());
	}
	
	/**
	 * 测试添加文档
	 * @throws IOException 
	 */
	
	@Test
	void testAddDocument() throws IOException {
		User user = new User("BLU",3);
		//创建请求
		IndexRequest blu_request = new IndexRequest("blu_index");
		//创建规则
		blu_request.id("1");
		blu_request.timeout(TimeValue.timeValueSeconds(1));
		//将数据放入请求
		IndexRequest source = blu_request.source(JSON.toJSONString(user),XContentType.JSON);
		//客户端发送请求,获取响应的结果
		IndexResponse indexResponse = client.index(blu_request, RequestOptions.DEFAULT);
		System.out.println(indexResponse.toString());
		System.out.println(indexResponse.status());
	}
	
	/**
	 * 判断文档是否存在
	 * @throws IOException
	 */
	@Test
	void testIsExist() throws IOException {
		GetRequest getRequest = new GetRequest("blu_index","1");
		//不获取返回的_source的上下文
		getRequest.fetchSourceContext(new FetchSourceContext(false));
		getRequest.storedFields("_none_");
		boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
		System.out.println(exists);
	}
	
	/**
	 * 获得文档信息
	 * @throws IOException
	 */
	@Test
	void testGetDocument() throws IOException {
		
		GetRequest getRequest = new GetRequest("blu_index","1");
		GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
		//打印文档的内容
		System.out.println(getResponse.getSourceAsString());
	}
	
	/**
	 * 更新文档信息
	 * @throws IOException
	 */
	@Test
	void testUpdateDocument() throws IOException {
		UpdateRequest updateRequest = new UpdateRequest("blu_index","1");
		updateRequest.timeout("1s");
		User user = new User("BLU",22);
		updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
		UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
		System.out.println(updateResponse.status());
	}
	
	/**
	 * 删除文档数据
	 * @throws IOException
	 */
	@Test
	void testDeleteDocument() throws IOException {
		DeleteRequest deleteRequest = new DeleteRequest("blu_index","1");
		deleteRequest.timeout("1s");
		DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
		System.out.println(deleteResponse.status());
	}
	
	/**
	 * 批量插入数据
	 * @throws IOException
	 */
	@Test
	void testBulkDocument() throws IOException {
		BulkRequest bulkRequest = new BulkRequest();
		bulkRequest.timeout("1s");
		
		ArrayList<User> list = new ArrayList<User>();
		list.add(new User("BLU1",3));
		list.add(new User("BLU2",4));
		list.add(new User("BLU3",5));
		list.add(new User("BLU4",6));
		list.add(new User("BLU5",7));
		list.add(new User("BLU6",21));
		
		for (int i = 0; i < list.size(); i++) {
			bulkRequest.add(new IndexRequest("blu_index").id(""+(i+1)).source(JSON.toJSONString(list.get(i)),XContentType.JSON));
		}
		
		BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
		System.out.println(bulkResponse.hasFailures());
		
	}
	
	@Test
	void testSearch() throws IOException {
		SearchRequest searchRequest = new SearchRequest("blu_index");
		//构建搜索条件
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		//QueryBuilders.termQuery精确匹配
		//QueryBuilders.matchAllQuery匹配所有
		TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "BLU2");
		sourceBuilder.query(termQueryBuilder);
		sourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));
		
		searchRequest.source(sourceBuilder);
		SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
		System.out.println(JSON.toJSONString(searchResponse.getHits()));
		for (SearchHit documentFields : searchResponse.getHits().getHits()) {
			System.out.println(documentFields.getSourceAsMap());
		}

		
	}
	
	
	
	
	
}

你可能感兴趣的:(ElasticSearch,SpringBoot,elasticsearch)