引入
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.8</version>
</dependency>
</dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
索引库
新建
@Test
public void createIndex() throws Exception {
//1、创建一个Settings对象,需要设置一个“cluster.name”属性
Settings settings = Settings.builder()
.put("cluster.name", "my-elasticsearch")
.build();
//2、创建一个TransportClient对象,PreBuilderTransportClient类创建对象,需要Settings对象
TransportClient client = new PreBuiltTransportClient(settings);
//3、向TransportClient对象中设置集群中的node列表
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
//4、使用TransportClient创建索引库
client.admin().indices()
//设置索引库的名称
.prepareCreate("blog")
//执行操作
.get();
//5、关闭TransportClient对象
client.close();
}
删除index
client.admin().indices()
.prepareDelete("hello")
.get();
设置mapping
设置index之后设置mapping
@Test
public void putMapping() throws Exception {
// 创建json对象
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type", "long")
.field("index", true)
.field("store", "true")
.endObject()
.startObject("title")
.field("type", "text")
.field("store", "true")
.field("analyzer", "ik_max_word")
.endObject()
.startObject("content")
.field("type", "text")
.field("store", "true")
.field("analyzer", "ik_max_word")
.endObject()
.endObject()
.endObject()
.endObject();
// 使用client对象设置mapping信息
client.admin().indices()
//设置要向哪个索引库中设置mapping
.preparePutMapping("blog")
//设置mapping的type名称
.setType("article")
//设置mapping的json数据
.setSource(builder)
//执行操作
.get();
//关闭client
client.close();
}
创建index的时候设置mapping
client.admin().indices()
//新建索引库的名称
.prepareCreate("blog2")
//设置mapping信息。后面是枚举类型
.setSource(mapping, XContentType.JSON)
.get();
aliase
logESIndex.addAliase("log_index", "log_index_all");
logESIndex.addAliase("log_index2", "log_index_all");
文档
新建
方式1:直接新建
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id", 1)
.field("title","测试文档的标题")
.field("content", "测试文档的内容")
.endObject();
// 使用client对象将文档写入索引库
client.prepareIndex()
//.prepareIndex("blog", "article")
//设置操作的索引库
.setIndex("blog")
//设置type名称
.setType("article")
//设置文档的id(_id)
.setId("1")
//设置文档信息
.setSource(builder)
//执行操作
.get();
方式2:使用对象新建
ObjectMapper objectMapper = new ObjectMapper();
//使用Objectmapper对象将java对象转换成json字符串
String json = objectMapper.writeValueAsString(article);
//使用client对象将文档写入索引库
client.prepareIndex("blog", "article", "2")
.setSource(json, XContentType.JSON)
.get();
删除
client.prepareDelete("blog", "article", "1")
//执行操作
.get();
修改
方式一:和新建一摸一样
client.prepareIndex("blog","article", "2")
.setSource(json, XContentType.JSON)
.get();
方式二:使用prepareUpdate
client.prepareUpdate("blog", "article", "2")
.setDoc(json, XContentType.JSON)
.get();
搜索
# 精确搜索
TermQueryBuilder builder = QueryBuilders.termQuery("title", "测试文档的标题");
# 正则搜索
RegexpQueryBuilder builder = QueryBuilders.regexpQuery("title", ".*"+"文档的标题"+".*");
# 排序
searchRequestBuilder.addSort("publish_time", SortOrder.DESC);
# 普通搜索
SearchResponse searchResponse = logESIndex.getClient()
.prepareSearch("log_index_all")
.setQuery(builder)
.addSort("field", SortOrder.ASC)
.get();
# 分组
# select field1, field2, sum(field3) from table_name group by field1, field2;
SearchResponse response = client.prepareSearch("test_index").setTypes("tweet")
.addAggregation(AggregationBuilders.terms("userAgg").field("user.keyword")
.subAggregation(AggregationBuilders.terms("sexAgg").field("sex.keyword")
.subAggregation(AggregationBuilders.sum("sumAgg").field("age")))) //求和要放到最内层的分组语句里面
//4、取查询结果
SearchHits searchHits = searchResponse.getHits();
//5、可以取查询结果的总记录数
System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
//6、取结果列表
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
Map<String, Object> source = hit.getSource();
System.out.println(source);
}
查询
根据id查询示例
@Test
public void searchById() throws Exception {
//1、创建一个client对象
//2、创建QueryBuilder查询对象
QueryBuilder builder = QueryBuilders.idsQuery()
.addIds("2");
//3、使用client的prepareQuery方法,执行查询
//设置查询的索引库
SearchResponse searchResponse = client.prepareSearch("blog")
//设置查询的type
.setTypes("article")
//设置查询条件
.setQuery(builder)
//执行查询
.get();
//4、取查询结果
SearchHits searchHits = searchResponse.getHits();
//5、可以取查询结果的总记录数
System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
//6、取结果列表
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
Map<String, Object> source = hit.getSource();
System.out.println(source);
}
//7、关闭client
client.close();
}
关键词查询TermQuery
QueryBuilder builder = QueryBuilders.termQuery("title", "寿星老");
QueryString查询
QueryBuilder builder = QueryBuilders.queryStringQuery("央行连续11日暂停公开市场操作").defaultField("title");
分页查询
设置起始行和size即可
SearchResponse searchResponse = client.prepareSearch("blog")
//设置查询的type
.setTypes("article")
//设置查询条件
.setQuery(builder)
//设置分页信息,起始的行号
.setFrom(0)
//每页显示的行数
.setSize(3)
//执行查询
.get();
高亮显示
@Test
public void searchByTermWithHighlighing() throws Exception {
QueryBuilder builder = QueryBuilders.termQuery("title", "人民币");
//3、使用client的prepareQuery方法,执行查询
//创建高亮显示的Builder对象
HighlightBuilder highlightBuilder = new HighlightBuilder()
//设置高亮显示的域
.field("title")
//前缀
.preTags("<em>")
//后缀
.postTags("</em>");
//设置查询的索引库
SearchResponse searchResponse = client.prepareSearch("blog")
//设置查询的type
.setTypes("article")
//设置查询条件
.setQuery(builder)
//设置分页信息,起始的行号
.setFrom(0)
//每页显示的行数
.setSize(3)
//设置高亮信息
.highlighter(highlightBuilder)
//执行查询
.get();
//4、取查询结果
SearchHits searchHits = searchResponse.getHits();
//5、可以取查询结果的总记录数
System.out.println("查询结果的总记录数:" + searchHits.getTotalHits());
//6、取结果列表
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
//获得返回的文档对象,使用map表示
Map<String, Object> source = hit.getSource();
//当前文档对象高亮的结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
System.out.println(source);
System.out.println(highlightFields);
//根据高亮显示的域的名称取结果
Text title = highlightFields.get("title").getFragments()[0];
System.out.println(title);
}
//7、关闭client
client.close();
}