最近在学习ES做了如下整理,这里安装就不说了,百度都有.这篇文章先介绍创建maven项目使用java api操作ES,后面会使用SpringBoot去集成ES,简单说下ES到底是什么?
Elasticsearc是基于lucene实现,隐藏复杂性,提供了简单易用的restful-api接口 java api接口(还有其他语言)
它是一个实时分布式搜索引擎.它用于全文搜素,结构化对比和分析.
我们还要知道它的基本术语:
知道这些我们就可以去做一些简单的操作了.
但是在操作之前我们还是把官网贴出来方便学习:
官网
java api
github地址
看完这些绝对够了.哈哈
<dependency>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
<version>5.2.2version>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>transportartifactId>
<version>5.2.2version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.9.0version>
dependency>
package cn.zhangyu.util;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ElasticSearchClient {
public PreBuiltTransportClient getClient() {
Settings settings = Settings.builder().put("cluster.name","my-application").build();
PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("10.13.82.17"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
}
package cn.zhangyu;
import cn.zhangyu.util.ElasticSearchClient;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class ElasticSearchApp {
ElasticSearchClient elasticSearchClient = new ElasticSearchClient();
//创建索引
@Test
public void createIndex() {
elasticSearchClient.getClient().admin().indices().prepareCreate("blog2").get();
elasticSearchClient.getClient().close();
}
//删除索引
public void delIndex(){
elasticSearchClient.getClient().admin().indices().prepareDelete("blog2").get();
elasticSearchClient.getClient().close();
}
//新建文档 源数据为json字符串
@Test
public void createDocumentByJson(){
//1 准备文档数据
String json = "{" + "\"id\":\"1\"," + "\"title\":\"基于Lucene的搜索服务器\","
+ "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" + "}";
//2 创建文档
IndexResponse response = elasticSearchClient.getClient().prepareIndex("blog", "article", "1")
.setSource(json).execute().actionGet();
//3 结果
System.out.println("index:" + response.getIndex());
System.out.println("type:" + response.getType());
System.out.println("String:" + response.toString());
//4 关闭连接
elasticSearchClient.getClient().close();
}
//新建文档(源数据map方式添加json)
@Test
public void createDocumentByMap(){
//1 准备数据源
Map<String,Object> json = new HashMap<>();
json.put("id","2");
json.put("title","基于Lucen的搜索服务器");
json.put("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
//2 创建文档
IndexResponse response = elasticSearchClient.getClient().prepareIndex("blog", "article", "2")
.setSource(json).execute().actionGet();
//3 打印返回的结果
System.out.println("index:" + response.getIndex());
System.out.println("type:" + response.getType());
System.out.println("id:" + response.getId());
System.out.println("version:" + response.getVersion());
System.out.println("result:" + response.getResult());
//4 关闭连接
elasticSearchClient.getClient().close();
}
//新建文档(源数据es构建器添加json)
@Test
public void createIndexByEs() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
.field("id", "3")
.field("title", "基于Lucene的搜索服务器")
.field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")
.endObject();
IndexResponse indexResponse = elasticSearchClient.getClient().prepareIndex("blog", "article", "3")
.setSource(builder).execute().actionGet();
//3 打印结果
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("result:" + indexResponse.getResult());
//4 关闭连接
elasticSearchClient.getClient().close();
}
//搜索数据(单索引)
@Test
public void getData(){
//1 查询文档
GetResponse response = elasticSearchClient.getClient()
.prepareGet("blog","article","1")
.get();
//2 打印结果
System.out.println(response.getSourceAsString());
//3 关闭连接
elasticSearchClient.getClient().close();
}
//搜索数据(多索引)
@Test
public void getMultiData(){
//1 查询多个文档
MultiGetResponse responses = elasticSearchClient.getClient().prepareMultiGet()
//这里可以传递可变参数,即多个参数 (参考源码)
.add("blog", "article", "1","2","3","4","5")
// .add("blog", "article", "2")
// .add("blog", "article", "3")
// .add("blog", "article", "5")
.get();
//2 遍历结果 lambda表达式
responses.forEach(itemResponses -> System.out.println(itemResponses.getResponse().getSourceAsString()));
//3 关闭连接
elasticSearchClient.getClient().close();
}
//更新文档数据
@Test
public void updateData() throws IOException, ExecutionException, InterruptedException {
// 创建更新数据的请求对象
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("blog");
updateRequest.type("article");
updateRequest.id("3");
//会对没有的字段添加,已有的字段替换
updateRequest.doc(XContentFactory.jsonBuilder().startObject()
.field("title", "基于Lucene的搜索服务器")
.field("content",
"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。大数据前景无限")
.field("createDate", "2017-8-22").endObject());
//获取更新后的值
UpdateResponse updateResponse = elasticSearchClient.getClient().update(updateRequest).get();
//3 打印结果
System.out.println("index:" + updateResponse.getIndex());
System.out.println("type:" + updateResponse.getType());
System.out.println("id:" + updateResponse.getId());
System.out.println("version:" + updateResponse.getVersion());
System.out.println("result:" + updateResponse.getResult());
//4 关闭连接
elasticSearchClient.getClient().close();
}
//更新文档数据(upsert)
@Test
public void upsertData() throws Exception{
// 设置查询条件, 查找不到则添加
IndexRequest indexRequest = new IndexRequest("blog", "article", "4");
indexRequest.source(XContentFactory.jsonBuilder().startObject()
.field("title", "搜索服务器")
.field("content","它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。")
.endObject());
//设置更新,查找更新下面的设置
UpdateRequest updateRequest = new UpdateRequest("blog", "article", "4");
updateRequest.doc(XContentFactory.jsonBuilder().startObject()
.field("user","张3").endObject()).upsert(indexRequest);
elasticSearchClient.getClient().update(updateRequest).get();
//4 关闭连接
elasticSearchClient.getClient().close();
}
//删除文档数据
@Test
public void delData(){
//1 删除文档
DeleteResponse deleteResponse = elasticSearchClient.getClient().prepareDelete("blog", "article", "4").get();
// 2 打印返回的结果
System.out.println("index:" + deleteResponse.getIndex());
System.out.println("type:" + deleteResponse.getType());
System.out.println("id:" + deleteResponse.getId());
System.out.println("version:" + deleteResponse.getVersion());
System.out.println("found:" + deleteResponse.getResult());
}
}
//查询所有
@Test
public void matchAllQuery(){
//1 执行查询
SearchResponse searchResponse = elasticSearchClient.getClient().prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.matchAllQuery()).get();
// 2 打印结果
SearchHits hits = searchResponse.getHits();
System.out.println("count :" + hits.getTotalHits() +" 条");
hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
// 3 关闭连接
elasticSearchClient.getClient().close();
}
//对所有字段分词查询
@Test
public void queryStringQuery(){
SearchResponse searchResponse = elasticSearchClient.getClient()
.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.queryStringQuery(" lucene")).get();
// 2 打印结果
SearchHits hits = searchResponse.getHits();
System.out.println("count :" + hits.getTotalHits() +" 条");
hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
// 3 关闭连接
elasticSearchClient.getClient().close();
}
/*通配符查询
*:表示多个字符(任意的字符)
?:表示单个字符
*
*/
@Test
public void wildcardQuery(){
//通配符查询
SearchResponse searchResponse = elasticSearchClient.getClient()
.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.wildcardQuery("content", "*全*")).get();
//打印查询结果
SearchHits hits = searchResponse.getHits();
System.out.println("count :" + hits.getTotalHits() +" 条");
hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
//关闭连接
elasticSearchClient.getClient().close();
}
//词条查询
@Test
public void termQuery(){
SearchResponse searchResponse = elasticSearchClient.getClient()
.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.termQuery("content","它")).get();
//打印查询结果
SearchHits hits = searchResponse.getHits();
System.out.println("count :" + hits.getTotalHits() +" 条");
hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
//关闭连接
elasticSearchClient.getClient().close();
}
//模糊查询
@Test
public void fuzzyQuery(){
SearchResponse searchResponse = elasticSearchClient.getClient()
.prepareSearch("blog").setTypes("article")
.setQuery(QueryBuilders.fuzzyQuery("title","lucene")).get();
SearchHits hits = searchResponse.getHits();
System.out.println("count :" + hits.getTotalHits() +" 条");
hits.forEach(hit -> System.out.println(hit.getSourceAsString()));
elasticSearchClient.getClient().close();
}