06-springboot集成ES详解

springboot集成ES详解

1、new springboot项目 (看项目记得配环境,如jdk)

06-springboot集成ES详解_第1张图片

问题:一定要保证我们导入的依赖和我们es版本一致

编写config配置类

package com.kuang.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 ElasticSerachClientConfig {

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

关于索引的API操作详解

要开启elasticsearch客户端哦~

package com.kuang;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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.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 java.io.IOException;

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

	//测试索引的创建 request
	@Test
	void testCreateIndex() throws IOException {
		//1.创建索引请求
		CreateIndexRequest request = new CreateIndexRequest("kuang_index");
		//2.客户端执行请求
		CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
		System.out.println(createIndexResponse);

	}
	//测试获取索引,只能判断是否存在
	@Test
	void testExistIndex() throws IOException {
		GetIndexRequest request = new GetIndexRequest("kuang_index");
		boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
		System.out.println(exists); //true
	}
	@Test
	void testDeleteIndex() throws IOException {
		DeleteIndexRequest request = new DeleteIndexRequest("kuang_index");
		AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
		System.out.println(delete.isAcknowledged()); //true
	}
}

关于文档的API操作详解

<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
    <version>1.2.61version>
dependency>

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class User {
    private String name;
    private int age;
}

测试类

//测试添加文档
	@Test
	void testAdd() throws IOException {
		//创建对象
		User user = new User("狂神说", 3);
		//创建请求
		IndexRequest request = new IndexRequest("kuang_index");

		//规则 put /kuang_index/_doc/1
		request.id("1");
		request.timeout(TimeValue.timeValueSeconds(1));
		request.timeout("1s");

		//将我们的数据放入请求 json
		request.source(JSON.toJSONString(user), XContentType.JSON);
		//客户端发送请求
		IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
		System.out.println(indexResponse.toString());
		System.out.println(indexResponse.status());//CREATED
	}
//获取文档,判断是否存在 get /index/_doc/1
	@Test
	void testIsExists() throws IOException {
		GetRequest getRequest = new GetRequest("kuang_index", "1");
		//不获取返回的_source的上下文了
		getRequest.fetchSourceContext(new FetchSourceContext(false));
		getRequest.storedFields("_none_");
		boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
		System.out.println(exists);//true

	}
	//获取文档的信息
	@Test
	void testGetDocument() throws IOException {
		GetRequest getRequest = new GetRequest("kuang_index", "1");
		GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
		System.out.println(getResponse.getSourceAsString());//打印文档的内容 {"age":3,"name":"狂神说"}
		System.out.println(getResponse);//返回的全部内容和命令式是一样的
	}
	//更新文档的信息
	@Test
	void testUpdateRequest() throws IOException {
		UpdateRequest updateRequest = new UpdateRequest("kuang_index", "1");
		updateRequest.timeout("1s");
		User user = new User("狂神说Java", 18);
		updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);

		UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
		System.out.println(update.status());//OK
	}
	//删除文档记录
	@Test
	void testDeleteRequest() throws IOException {
		DeleteRequest request = new DeleteRequest("kuang_index", "1");
		request.timeout("1s");
		DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
		System.out.println(delete.status());//OK
	}
	// 特殊的,真的项目一般都会批量插入数据!
	@Test
	void testBulkRequest() throws IOException {
		BulkRequest bulkRequest = new BulkRequest();
		bulkRequest.timeout("10s");
		ArrayList<User> userList = new ArrayList<>();
		userList.add(new User("kuangshen1",3));
		userList.add(new User("kuangshen2",3));
		userList.add(new User("kuangshen3",3));
		userList.add(new User("zhangsan1",3));
		userList.add(new User("zhangsan2",3));
		userList.add(new User("zhangsan3",3));
		//批处理请求
		for (int i=0;i<userList.size();i++){
			//批量更新和批量删除,就在这里修改对应的请求就可以了 不设置id会有随机id 乱七八糟的
			bulkRequest.add(
					new IndexRequest("kuang_index").id(""+(i+1)).source(
							JSON.toJSONString(userList.get(i)),XContentType.JSON));
		}
		BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
		System.out.println(bulk.hasFailures());// 是否失败 false 代表成功
	}
	//查询
	// searchRequest 搜索请求
	//SearchSourceBuilder 条件构造
	// HighlightBuilder 构建高亮
	//termQueryBuilder  精确查询
	@Test
	void testSearch() throws IOException {
		SearchRequest searchRequest = new SearchRequest("kuang_index");
		//构建搜索条件
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		//查询条件 我们可以使用QueryBuilders 工具来实现
		//termQuery 精确查询
		//QueryBuilders.matchAllQuery();  匹配所有
        //中文查不出来,name改为name.keyword
		TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhangsan1");
//		MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
		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()));
		System.out.println("=================");
		for (SearchHit documentFields:searchResponse.getHits().getHits()){
			System.out.println(documentFields.getSourceAsMap());
		}

	}

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