StringBoot集成Elasticsearch

2022-03-23 20:11:32 浏览数 (1)

官方文档 此处

本文使用Elasticsearch版本为7.8.0

创建一个项目 勾选es依赖

编译版本一定是8以上

默认集成的版本 跟我们本地安装的版本不一样

自己指定跟自己es版本匹配即可

代码语言:javascript复制
<properties>
		<java.version>1.8</java.version>
		<!--自己定义es版本-->
        <elasticsearch.version>7.8.0</elasticsearch.version>
	</properties>

本文的所有依赖

代码语言:javascript复制
	<properties>
		<java.version>1.8</java.version>
		<!--自己定义es版本-->
        <elasticsearch.version>7.8.0</elasticsearch.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<!--json-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.76</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

编写一个配置类创建连接es的客户端

代码语言:javascript复制
@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        //配置客户端连接es信息
                        new HttpHost("localhost", 9200, "http")
                ));
        return client;
    }

}

测试索引操作

测试创建索引

代码语言:javascript复制
@SpringBootTest
class FeiEsApiApplicationTests {

	@Autowired
	private RestHighLevelClient restHighLevelClient;

	/**
	 * 测试索引的创建
	 */
	@SneakyThrows
	@Test
	void testCreate(){
		//1.创建索引请求
		CreateIndexRequest createIndexRequest = new CreateIndexRequest("fei_index");
        //2.客户端执行创建请求
		CreateIndexResponse response = restHighLevelClient
				.indices()
				.create(createIndexRequest, RequestOptions.DEFAULT);
		System.out.println(response);
	}


}

获取索引

代码语言:javascript复制
/**
	 * 测试获取索引
	 */
	@SneakyThrows
	@Test
	void testGetIndex()  {
		GetIndexRequest request = new GetIndexRequest("fei_index");
		boolean exists = restHighLevelClient
				.indices()
				//判断索引是否存在
				.exists(request, RequestOptions.DEFAULT);
		System.out.println(exists);
	}

删除索引

代码语言:javascript复制
@SneakyThrows
	@Test
	void testDel(){
		//创建删除索引请求
		DeleteIndexRequest request = new DeleteIndexRequest("fei_index");
		//执行删除
		AcknowledgedResponse response = restHighLevelClient
				.indices()
				.delete(request, RequestOptions.DEFAULT);
		System.out.println(request);
	}

文档操作

添加文档

代码语言:javascript复制
/**
	 * 测试添加文档
	 */
	@SneakyThrows
	@Test
	void testAddDocument(){
    	//创建对象
		User user = new User("飞飞",24);
		//创建请求
		IndexRequest request = new IndexRequest("fei_index");
        //设置规则
		request.id("1");
		request.timeout(TimeValue.timeValueSeconds(1));
		//将我们的数据放入请求  Json
		request.source(JSON.toJSONString(user), XContentType.JSON);
	    //客户端发送请求  获取响应结果
		IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
		System.out.println(response.toString());
	}

获取文档

代码语言:javascript复制
/**
	 * 获取文档  判断是否存在
	 */
	@SneakyThrows
	@Test
	void testIsGet(){
		GetRequest request = new GetRequest("fei_index","1");
		//不获取返回的_source 上下文了
		request.fetchSourceContext(new FetchSourceContext(false));
		request.storedFields("_none_");
        //判断是否存在
		boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
		System.out.println(exists);
	}

获取文档内容

代码语言:javascript复制
/**
	 * 获取文档信息
	 */
	@SneakyThrows
	@Test
	void testGetDocument(){
		 GetRequest request = new GetRequest("fei_index", "1");
		 //获取文档信息
		 GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
		 //打印文档内容
		 System.out.println(response.getSourceAsString());

	}

更新文档信息

代码语言:javascript复制
//更新文档信息
	@Test
	@SneakyThrows
	void testGetUpd(){
		UpdateRequest request = new UpdateRequest("fei_index","1");
		//设置超时时间
		request.timeout("1s");
		User user = new User("阿飞", 18);
		//转成json数据    数据的类型
		request.doc(JSON.toJSONString(user),XContentType.JSON);
		//执行更新打印结果
		UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
		System.out.println(update);
	}

删除文档信息

代码语言:javascript复制
/**
	 * 删除文档信息
	 */
	@SneakyThrows
	@Test
	void testDelDoc(){
		//创建删除请求  删除 fei_index索引的id为二的文档
		DeleteRequest request = new DeleteRequest("fei_index","2");
		DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
		System.out.println(delete);
	}

批量操作

代码语言:javascript复制
/**
	 * 特殊的,   批量插入数据
	 */
	@SneakyThrows
	@Test
	void testBulkReq(){
		//创建批量请求
		BulkRequest request = new BulkRequest();
		//设置超时时间
		request.timeout("5s");
		ArrayList<User> list = new ArrayList<>();
		list.add(new User("张三",20));
		list.add(new User("张四",21));
		list.add(new User("张五",22));
		list.add(new User("张六",23));
		list.add(new User("张七",24));

		for (int i = 0; i < list.size(); i  ) {
			//插入和删除写对应的请求就可以了
			 request.add(new IndexRequest("fei_index")
			 .id("" (i 1))
					 .source(JSON.toJSONString(list.get(i)),XContentType.JSON));
		}
		BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
	}

查询

代码语言:javascript复制
/**
	 * 查询
	 */
	@SneakyThrows
	@Test
	void testSearch(){
		SearchRequest request = new SearchRequest("fei_index");
		//构建搜索的条件      term精准匹配
		SearchSourceBuilder builder = new SearchSourceBuilder();
		TermQueryBuilder query = QueryBuilders.termQuery("name", "张三");
		builder.query(query);
		//分页
		builder.from(0);
		builder.size(3);
		builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
	    //条件放入请求
		request.source(builder);
	    //执行
		SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
		//打印结果
		System.out.println(JSON.toJSONString(search.getHits()));
	}

0 人点赞