ElasticSearch 是什么
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
什么是全文检索
全文检索是指计算机索引程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置,当用户查询时,检索程序就根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。这个过程类似于通过字典中的检索字表查字的过程。全文搜索搜索引擎数据库中的数据。
spring data elasticsearch ElasticsearchRepository
基本操作与jpa相同 参考:https://blog.csdn.net/topdandan/article/details/81436141
条件分页查询
public void test(){ //分页 Pageable pageable =PageRequest.of(0,20); //组合查询条件 SearchQuery nativeSearchQueryBuilder =new NativeSearchQueryBuilder() //条件 .withQuery(QueryBuilders.matchPhraseQuery("filed","value") //排序 .withSort(SortBuilders.fieldSort("filed").order(SortOrder.ASC)) .withPageable(pageable) .build(); Page<Object> page =elasticsearchRepository.search(nativeSearchQueryBuilder); return page.getContent(); }
聚合查询
public void test() {
//聚合字段 name为自定义聚合名称 field属性名称 ValueCountAggregationBuilder builder = AggregationBuilders.count("name").field("field");
//组合查询 SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(QueryBuilders.matchPhraseQuery("field","value")) .addAggregation(builder ) .build();
//分页信息 Page<Object> saleAmount = elasticsearchRecordRepository.search(searchQuery);
//elasticsearchTemplate取得聚合结果 此方法只取聚合结果 Aggregation counts=elasticsearchTemplate.query(searchQuery,searchResponse -> { InternalValueCount count=(InternalValueCount)searchResponse.getAggregations().asList().get(0); return sum; }); System.out.println(saleAmount);
}
public void test() {
TermsAggregationBuilder tb = AggregationBuilders.terms("name").field("field") SearchQuery searchQuery =new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchPhraseQuery("field","value")) .withIndices(INDEX) .withTypes(TYPE) .addAggregation(tb) .build();
//获取聚合值 Aggregations aggregations =elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { @Override public Aggregations extract(SearchResponse searchResponse) { return searchResponse.getAggregations(); } });
List<Map> mapList=new ArrayList<>;
//将聚合的值转换为map集合 Map<String,Aggregation> map =aggregations.asMap(); for (String s :map.keySet()){ StringTerms stringTerms = (StringTerms) map.get(s);
//获取所有的桶 List<StringTerms.Bucket> list =stringTerms.getBuckets(); for (Terms.Bucket bucket :list){ System.out.println(" "+bucket.getKeyAsString()+ "----"+bucket.getDocCount() );
String name = bucket.getKeyAsString();
long count = bucket.getDocCount();
Map a = new HashMap();
a.put("name",name);
a.put("conut",count);
mapList.add(a); } } }