https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.6/java-rest-high.html
创建一个springboot的maven的项目 导入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.6.2</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.6.2</version>
</dependency>
@Test
public void contextLoads() throws IOException {
// 创建和es的连接
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")
//,new HttpHost("localhost", 9200, "http")
));
// 创建一个请求
GetRequest getRequest = new GetRequest(
"test5",
"doc",
"1");
// 判断是否存在一个文档
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
client.close();
}
@Test
public void contextLoads() throws IOException {
// 创建和es的连接
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")
//,new HttpHost("localhost", 9200, "http")
));
// 查询
// 创建一个查询请求对象
SearchRequest searchRequest = new SearchRequest();
// 创建查询条件的对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 查询全部的数据
// searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// 按照条件进行查询
searchSourceBuilder.query(QueryBuilders.termQuery("name","hong"));
// 将查询对象放到请求对象里面
searchRequest.source(searchSourceBuilder);
// 设置请求的索引
searchRequest.indices("test3");
// 设置请求的类型
searchRequest.types("_doc");
// 设置查询类型
searchRequest.searchType(SearchType.QUERY_THEN_FETCH);
// 进行查询
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
// 获取返回的数据并且打印
SearchHits hits = search.getHits();
// 得到数据的个数
System.out.println(hits.getTotalHits());
client.close();
}
}
首先存入一条数据 i like eating and kuing 默认分词器应该将内容分为 “i” “like” “eating” “and” “kuing”
must(QueryBuilders) : AND
mustNot(QueryBuilders): NOT
should: : OR
@Test
public void testQueryBuilder2() {
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("user", "kimchy"))
.mustNot(QueryBuilders.termQuery("message", "nihao"))
.should(QueryBuilders.termQuery("gender", "male"));
searchFunction(queryBuilder);
}
QueryBuilders.matchQuery(“supplierName”,param)
会将搜索词分词,再与目标查询字段进行匹配,若分词中的任意一个词与目标字段匹配上,则可查询到。
param = “i” 可查出i
param = “i li” 可查出
param = “i like” 可查出
param = “i like eat” 可查出
param = “and” 可查出
param = “kuing” 可查出
先查询出符合条件的所有的数据之后再分页
searchSourceBuilder
.query(QueryBuilders.matchAllQuery())
.from(0).size(2);
将索引里面的东西都查询出来
searchSourceBuilder.query(QueryBuilders.matchAllQuery())
排序
就是将数据查询出来之后,可以进行分页,可以进行排序
searchSourceBuilder
.query(QueryBuilders.matchAllQuery())
.from(0)
.size(3)
.sort("age", SortOrder.ASC);
过滤
searchSourceBuilder
.query(QueryBuilders.matchAllQuery())
.from(0)
.size(3)
.sort("age", SortOrder.ASC)
.postFilter(QueryBuilders.rangeQuery("age").from(30).to(31));
安装匹配度进行查询,就是每条数据的得分,得分越高,越可以查询出来
searchSourceBuilder
.query(QueryBuilders.matchAllQuery())
.from(0)
.size(3)
.sort("age", SortOrder.ASC)
.postFilter(QueryBuilders.rangeQuery("age").from(30).to(31))
.explain(true);
multiMatchQuery(“text”, “field1”, “field2”…); 匹配多个字段, field有通配符忒行
我们要查询的值不知道在哪个字段,所以需要多字段进行匹配,只要有一个字段符合条件,那么就可以匹配出来了
searchSourceBuilder
.query(QueryBuilders.multiMatchQuery("jing","name","age"))
.from(0)
.size(3)
.sort("age", SortOrder.ASC)
.postFilter(QueryBuilders.rangeQuery("age").from(30).to(31))
.explain(true);
根据值去每个字段进行模糊查询 +代表必须含有 -代表不能含有
//查询文档中含必须含有changge,不含有hejiu的文档(会每个字段去查询)+代表必须含有 -代表不能含有
QueryBuilder builder = QueryBuilders.queryStringQuery("+changge -hejiu");
可以按特定的字段进行模糊查询
searchSourceBuilder
.query(QueryBuilders.queryStringQuery("name:tome*"))
指定字段进行模糊查询
QueryBuilder builder =
QueryBuilders.commonTermsQuery("name","jing");
说明:根据值去每个字段进行模糊查询 只要有一个符合就会返回该文章
//只要所有字段中,含有changge或hejiui的都返回
QueryBuilder builder =
QueryBuilders.simpleQueryStringQuery("jing");
精准匹配
字段的值必须是这个才可以查询出来
searchSourceBuilder.query(QueryBuilders.termQuery("name","hong"));
在ES里面所有的聚合实例都由AggregationBuilders类提供静态方法构造,
(1)统计某个字段的数量
ValueCountBuilder vcb= AggregationBuilders.count("count_uid").field("uid");
(2)去重统计某个字段的数量(有少量误差)
CardinalityBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid");
(3)聚合过滤
FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001"));
(4)按某个字段分组
TermsBuilder tb= AggregationBuilders.terms("group_name").field("name");
(5)求和
SumBuilder sumBuilder= AggregationBuilders.sum("sum_price").field("price");
(6)求平均
AvgBuilder ab= AggregationBuilders.avg("avg_price").field("price");
(7)求最大值
MaxBuilder mb= AggregationBuilders.max("max_price").field("price");
(8)求最小值
MinBuilder min= AggregationBuilders.min("min_price").field("price");
(9)按日期间隔分组
DateHistogramBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date");
(10)获取聚合里面的结果
TopHitsBuilder thb= AggregationBuilders.topHits("top_result");
(11)嵌套的聚合
NestedBuilder nb= AggregationBuilders.nested("negsted_path").path("quests");
(12)反转嵌套
AggregationBuilders.reverseNested("res_negsted").path("kps ");
searchSourceBuilder对象里面有一个方法aggregation() 参数是聚合函数对象
先按照查询条件查询出数据,之后再进行聚合查询
// 创建查询条件的对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder aggration = AggregationBuilders.terms("by_age").field("age");
searchSourceBuilder
// .query(QueryBuilders.multiMatchQuery("jing","name","age"))
.query(QueryBuilders.matchAllQuery())
.aggregation(aggration);
聚合分组之后,获取分组的个数
// 进行查询
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
// 根据分组的名字进行获取,获取分组聚合之后的信息
Terms terms = search.getAggregations().get("by_age");
for(Terms.Bucket entity:terms.getBuckets()){
Object key = entity.getKey();
long docCount = entity.getDocCount();
System.out.println(key+"@"+docCount);
}
以下是按名字进行分组,之后计算分组之后的每个人分数的和
// 创建查询条件的对象
SearchSourceBuilder searchSourceBuilder =
new SearchSourceBuilder();
// 按名字进行分组
TermsAggregationBuilder nameaggration =
AggregationBuilders.terms("by_name").field("name");
// 按分数进行求和
SumAggregationBuilder field =
AggregationBuilders.sum("by_score").field("score");
将两个聚合对象连起来
nameaggration.subAggregation(field);
searchSourceBuilder
// .query(QueryBuilders.multiMatchQuery("jing","name","age"))
.query(QueryBuilders.matchAllQuery())
.aggregation(nameaggration);
获取结果,也就是获取每个人的成绩和
// 进行查询
SearchResponse search =
client.search(searchRequest, RequestOptions.DEFAULT);
Terms nameterms = search.getAggregations().get("by_name");
for(Terms.Bucket entity:nameterms.getBuckets()){
Sum sum = entity.getAggregations().get("by_age");
System.out.println("和:"+sum);
}
// 将查询对象放到请求对象里面
searchRequest.source(searchSourceBuilder);
// 设置请求的索引,以下两种方法都可以
searchRequest.indices("test3","test2");
searchRequest.indices("test*");
// 设置请求的类型
searchRequest.types("_doc","class");
searchRequest.types("_doc*");
// 设置查询类型
searchRequest.searchType(SearchType.QUERY_THEN_FETCH);