ElasticSearch集成SpringBoot实践
Search API
Search Request,用于搜索文档,聚合,相关的任何操作,还提供了高亮显示结果文档的方法
//创建,如果没有参数,会对所有索引运行 SearchRequest searchRequest = new SearchRequest(); //大多数搜索参数都能添加到SearchSourceBuilder,为进入搜索请求主体内容提供setter SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //添加match_all查询到SearchSourceBuilder searchSourceBuilder.query(QueryBuilders.matchAllQuery()); //将SearchSourceBuilder添加到SeachRequest searchRequest.source(searchSourceBuilder);
使用SearchSourceBuilder,大多数控制搜索行为的选项都可以在SearchSourceBuilder上设置
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.termQuery("user", "kimchy")); sourceBuilder.from(0); sourceBuilder.size(5); //设置超时时间控制允许搜索花费多长时间 sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
构建查询,搜索查询是使用QueryBuilder对象创建的,ES的查询DSL支持的每一种搜索查询类型都有一个QueryBuilder
//创建一个全文匹配查询,在字段user上匹配文本kimchy MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("user", "kimchy"); //创建后,用QueryBuilder对象提供的放啊来配置它创建的搜索查询选项 //启用模糊查询 matchQueryBuilder.fuzziness(Fuzziness.AUTO); //设置前缀长度选项 matchQueryBuilder.prefixLength(3); //最大扩展 matchQueryBuilder.maxExpansions(10);
QueryBuilder可使用QueryBuilder实用程序类创建对象
无论什么方法创建它,QueryBuilder对象都必须添加到SearchSourceBuilder
searchSourceBuilder.query(matchQueryBuilder);
ES查询在java中的实现
ES java api相关体系