5、Springboot整合Elasticsearch
Springboot整合Elasticsearch
首先,我们需要先创建一个SpringBoot项目,可参考我之前编写的SpringBoot项目的创建
1、导入相关maven依赖
<!--elasticsearch检索服务依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
2、创建yml配置文件
server:
port: 8080
elasticsearch:
esSchema: http
esHost: 192.168.111.129:9200 #你的服务器地址,集群的话用逗号分隔
esUserName: elastic #账号
esPassword: elastic #你的elasticsearch密码
3、创建config配置文件
注意这里导入的是ES的client依赖
import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; @Configuration public class ElasticSearchClientConfig { @Value("${elasticsearch.esUserName}") private String userName; @Value("${elasticsearch.esPassword}") private String password; @Value("${elasticsearch.esSchema}") private String scheme; @Value("${elasticsearch.esHost}") private String esHost; public static RestHighLevelClient client = null; @Bean public RestHighLevelClient restHighLevelClient() { //不需要用户名和密码的认证 //client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", "9300", "http"))); //需要用户名和密码的认证 final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); RestClientBuilder restClientBuilder = RestClient.builder(init(esHost)) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); client = new RestHighLevelClient(restClientBuilder); return client; } /** * 若是ES集群处理方式 */ private HttpHost[] init(String list) { List<HttpHost> result=new ArrayList<>(); if(list.indexOf(",")==-1) { String[] hostPort=list.split(":"); HttpHost httpHost=new HttpHost(hostPort[0],Integer.parseInt(hostPort[1]),scheme); result.add(httpHost); }else { String[] hosts=list.split(","); for(int i=0;i<hosts.length;i++) { String[] hostPort=hosts[i].split(":"); HttpHost httpHost=new HttpHost(hostPort[0],Integer.parseInt(hostPort[1]),scheme); result.add(httpHost); } } HttpHost[] arr=new HttpHost[result.size()]; for(int i=0;i<result.size();i++) { arr[i]=result.get(i); } return arr; } }
4、创建实体类
创建一个实体类供ES插入文档时使用
import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class User { private String name; private String age; }
5、编写测试类
//这里注意导入的是ES的client依赖 @SpringBootTest class ElasticApplicationTests { @Autowired @Qualifier("restHighLevelClient") private RestHighLevelClient client; /** * 索引的创建,所有的请求都是用Request */ @Test void contextLoads() throws IOException { //创建索引的请求 CreateIndexRequest request = new CreateIndexRequest("chen_index"); //执行请求 CreateIndexResponse createIndexRequest = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(createIndexRequest); } /** * 获取索引,判断是否存在 */ @Test void testExistIndex() throws IOException { GetIndexRequest request= new GetIndexRequest("chen_index"); boolean exists = client.indices().exists(request,RequestOptions.DEFAULT); System.out.println(exists); } /** * 删除索引 */ @Test void testDeleteIndex() throws IOException { DeleteIndexRequest request = new DeleteIndexRequest("chen_index"); AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT); System.out.println(delete.isAcknowledged()); } /** * 创建文档 */ @Test void testAddDocument() throws IOException { User user = new User("CJZ","3"); IndexRequest request= new IndexRequest("chen_index"); //ES中的_id设为1 request.id("1"); request.timeout("1s"); //将数据放入请求 request.source(JSON.toJSONString(user), XContentType.JSON); //客户端发送请求 IndexResponse indexResponse = client.index(request,RequestOptions.DEFAULT); System.out.println(indexResponse.toString()); System.out.println(indexResponse.status()); } /** * 获取文档,判断是否存在 */ @Test void testGetDocument() throws IOException { GetRequest getRequest = new GetRequest("chen_index","1"); //new FetchSourceContext(false)代表不获取_source的上下文 getRequest.fetchSourceContext(new FetchSourceContext(false)); getRequest.storedFields("_none_"); boolean exists = client.exists(getRequest,RequestOptions.DEFAULT); System.out.println(exists); } /** * 获取文档信息 */ @Test void testGetDocumentInfo() throws IOException { GetRequest getRequest = new GetRequest("chen_index","1"); GetResponse getResponse = client.get(getRequest,RequestOptions.DEFAULT); System.out.println(getResponse); //获取全部信息 System.out.println(getResponse.getSourceAsString()); //只获取_source中的信息 } /** * 更新文档信息 */ @Test void testUpdateDocumentInfo() throws IOException { UpdateRequest updateRequest = new UpdateRequest("chen_index","1"); updateRequest.timeout("1s"); User user = new User("CCC","18"); updateRequest.doc(JSON.toJSONString(user),XContentType.JSON); UpdateResponse updateResponse = client.update(updateRequest,RequestOptions.DEFAULT); System.out.println(updateResponse.status()); } /** * 删除文档信息 */ @Test void testDeleteDocumentInfo() throws IOException { DeleteRequest deleteRequest = new DeleteRequest("chen_index","1"); deleteRequest.timeout("1s"); DeleteResponse DeleteResponse = client.delete(deleteRequest,RequestOptions.DEFAULT); System.out.println(DeleteResponse.status()); } /** * 批量插入文档信息 */ @Test void testBulkDocumentInfo() throws IOException { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.timeout("10s"); ArrayList<User> userList = new ArrayList<>(); userList.add(new User("CCC1","1")); userList.add(new User("CCC2","2")); userList.add(new User("CCC3","3")); for(int i = 0; i < userList.size(); i++){ bulkRequest.add( new IndexRequest("chen_index") .id(""+(i+1)) .source(JSON.toJSONString(userList.get(i)),XContentType.JSON) ); } BulkResponse bulkItemResponses = client.bulk(bulkRequest,RequestOptions.DEFAULT); //是否失败,false为否,true为是 System.out.println(bulkItemResponses.hasFailures()); } /** * 条件获取文档信息 */ @Test void testSearch() throws IOException { //SearchRequest搜索请求的索引 SearchRequest searchRequest = new SearchRequest("student"); //构建搜索条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // /** * 查询条件,使用QueryBuliders工具来实现 * TermQueryBuilder 精确查询 * MatchQueryBuilder 模糊查询 * HighlightBuilder 高亮构建 */ TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age","15"); //MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name","王"); searchSourceBuilder.query(termQueryBuilder); //分页 //searchSourceBuilder.from(); //searchSourceBuilder.size(); searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT); //获取全部信息 System.out.println(JSON.toJSONString(searchResponse.getHits())); //只获取_source中的信息 for(SearchHit documentFields:searchResponse.getHits().getHits()){ System.out.println(documentFields.getSourceAsMap()); } } }