1、本地安装elasticsearch服务,具体过程见上一篇文章(安装和配置elasticsearch服务集群)
2、修改项目中pom文件,引入搜索相关jar包
org.springframework.boot spring-boot-starter-data-elasticsearch org.springframework.boot spring-boot-starter-jdbc
2、在application.yml文件中添加elasticsearch配置信息
spring: #elasticsearch配置 data: elasticsearch: #ElasticsearchProperties cluster-name: elastic #默认为elasticsearh cluster-nodes: 192.168.97.88:9300,192.168.97.88:9301 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
3、编写elasticsearch操作的相关类
(1)、获取elasticsearch客户端
//获取elasticsearch客户端String hostName = "192.168.97.88" ; //本地elasticsearch的yml配置文件中写的IP地址Integer port = 9200 ; //远程链接的端口号为9200RestClient restClient = RestClient.builder(new HttpHost(hostName, port)).build();/*//如果想要获取阿里云上的elasticsearch客户端,代码如下final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("阿里云elasticsearch用户名", "阿里云elasticsearch密码"));RestClient restClient = RestClient.builder(new HttpHost("阿里云elasticsearch的ip", 9200)) .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }).setMaxRetryTimeoutMillis(5 * 60 * 1000) //设置超时时间 .build();*/
(2)、查看索引是否存在 (索引必须为全小写)
//查看 demoIndex 索引是否存在Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.emptyMap());System.out.println(isExist.getStatusLine().getStatusCode());
(3)、索引不存在,创建索引
//查看 demoIndex 索引是否存在Response isExist = restClient.performRequest("HEAD","/demoindex" , Collections.emptyMap());int status = isExist.getStatusLine().getStatusCode();if( status == 404){ //不存在索引,创建索引 String method = "PUT"; String endpoint = "demoindex"; Response response = restClient.performRequest(method, "/" + endpoint); System.out.println(EntityUtils.toString(response.getEntity()));}
(4)、索引已经创建存在,我们接下来进行索引的 增删改查 操作
①、新增索引数据
//手动拼写一个符合要求的json串 json串的格式为:{"field1":"value1","field2":"value2"}String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch\"" + "}";HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);//发送一个请求,将json转换的实体发送到es,并常见索引,索引主键id=1Response indexResponse = restClient.performRequest( "PUT", "/" + "demoindex" + "/" + "demoindex" + "/1", Collections.emptyMap(), entity);//获取结果中的实体,查看是否新增成功System.out.println(EntityUtils.toString(indexResponse.getEntity()));
得到如下结果图,表示成功
②、批量新增索引数据 ( bulk )
//批量添加索引数据//手动拼写一个符合要求的json串// json串的格式为:// { "index" : { "_id" : "1" }} //这里为手动赋值id,也可以{ "index" : { }}为es自动设置id id相同时后添加的数据会覆盖之前添加的数据// {"field1":"value1","field2":"value2"}// { "index" : { "_id" : "2" }}// {"field1":"value1","field2":"value2"}String json = "{ \"index\" : { \"_id\" : \"1\" }} \n" + "{" + "\"user\":\"kimchy1\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elasticsearch1\"" + "} \n"; //一定要加换行json += "{ \"index\" : { \"_id\" : \"2\" }} \n" + "{" + "\"user\":\"kimchy2\"," + "\"postDate\":\"2014-01-30\"," + "\"message\":\"trying out Elasticsearch2\"" + "}";//将字符串转换成http实体HttpEntity entity = new NStringEntity(json,ContentType.APPLICATION_JSON);//发送请求,并的到处理结果Response response = restClient.performRequest("POST","/demoindex/demoindex/_bulk",Collections.singletonMap("pretty","true"),entity);//获取结果中的实体,查看是否新增成功System.out.println(EntityUtils.toString(response.getEntity()));
得到如下结果图,则表示批量插入成功;若红框裱起来的位置为update表示修改成功
③、修改单个索引时去执行插入单个索引,将主键id设置为需要更改的索引id即可
④、删除指定索引
//删除指定id索引Response deleteResponse = restClient.performRequest( "DELETE", "/demoindex/demoindex/3", //删除id为 3 的索引 Collections.emptyMap());System.out.println(EntityUtils.toString(deleteResponse.getEntity()));
得到如下结果,表示删除成功
⑤、根据属性来删除对应索引
//根据属性值来删除索引//删除user="kimchy2"的索引String queryString = "{\n" + " \"query\": {\n" + "\"match_phrase\": {\"user\": \"kimchy2\"}\n" + "}\n" + "}\n";HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);Response deleteResponse = restClient.performRequest( "POST", "/demoindex/demoindex/_delete_by_query", Collections.emptyMap(),entity);System.out.println((EntityUtils.toString(deleteResponse.getEntity())));
得到如下结果图表示删除成功
⑥、删除所有索引数据
//删除所有索引数据String queryString = "";queryString = "{\n" + " \"query\": {\n" + "\"match_all\": {}\n" + "}\n" + "}\n";HttpEntity entity = new NStringEntity(queryString, ContentType.APPLICATION_JSON);Response deleteResponse = restClient.performRequest( "POST", "/demoindex/demoindex/_delete_by_query", Collections.emptyMap(),entity);System.out.println(EntityUtils.toString(deleteResponse.getEntity()));
⑦、搜索索引中的数据
//查询索引数据String queryStr = "{ \n" + "\"query\" : { \n" + "\"match_phrase\": { \"user\": { \"query\" : \"kimchy1\", \"boost\" :\"5\" }}}\n" + "}\n" + "}";HttpEntity entity = new NStringEntity(queryStr, ContentType.APPLICATION_JSON);Response response = restClient.performRequest("GET", "/demoindex/demoindex/" + "_search",Collections.singletonMap("pretty", "true"),entity);System.out.println(EntityUtils.toString(response.getEntity()));
得到查询结果
有关更多查询匹配方式请看下一篇文章