java使⽤elasticsearch进⾏模糊查询之must使⽤-项⽬中实际使
⽤
java使⽤elasticsearch进⾏多个条件模糊查询
⽂章说明:
1、本篇⽂章,本⼈会从java连接elasticsearch到查询结果⽣成并映射到具体实体类(涵盖分页功能)
2、代码背景:elasticsearch版本为:5.2.0;
3、本⼈以下代码是分别从两个索引中查询数据,再将两个数据进⾏整合,如果⼤家只需要分组查询,那么则选取⽂章中的分组查询部分代码
4、本⼈的实体类主要是按照layUI分页框架进⾏设计;实体⼤家可以根据⾃⼰的具体需求进⾏设计
⼀、java连接elasticsearch⼯具类
public class ESClientConnectionUtil {
public static TransportClient client=null;
public final static String HOST = "192.168.200.200"; //服务器部署ip 根据⾃⼰ip进⾏更改
public final static Integer PORT = 9301; //端⼝
public static TransportClient getESClient(){
System.setProperty("es.setty.runtime.available.processors", "false");
if (client == null) {
synchronized (ESClientConnectionUtil.class) {
try {
//设置集名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("ansport.sniff", true).build();
//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(new ByName(HOST), PORT));
} catch (Exception ex) {
ex.printStackTrace();
System.out.Message());
}
}
}
return client;
}
public static TransportClient getESClientConnection(){
if (client == null) {
System.setProperty("es.setty.runtime.available.processors", "false");
try {
//设置集名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("ansport.sniff", true).build();
//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(new ByName(HOST), PORT));
} catch (Exception ex) {
ex.printStackTrace();
System.out.Message());
}
}
return client;
}
//判断索引是否存在
public static boolean judgeIndex(String index){
client= getESClientConnection();
IndicesAdminClient adminClient;
//查询索引是否存在
adminClient= client.admin().indices();
IndicesExistsRequest request = new IndicesExistsRequest(index);
IndicesExistsResponse responses = ists(request).actionGet();
if (responses.isExists()) {
return true;
}
return false;
}
}
⼆、实体类
(⼀)分页实体总类
public class KnowledgeTopicListDTO {
private Long totalCount;//总条数
private Integer page;//页数
private Integer limit;//每页查询条数
private List<KnowledgeTopicDTO> topicDTOList;//每页显⽰数据的对象集合public Long getTotalCount() {
return totalCount;
}
public void setTotalCount(Long totalCount) {
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public List<KnowledgeTopicDTO> getTopicDTOList() {
return topicDTOList;
}
public void setTopicDTOList(List<KnowledgeTopicDTO> topicDTOList) {
}
}
(⼆)页⾯显⽰数据对象实体
public class KnowledgeTopicDTO {
private Long id;//知识主题id
private String name;//知识主题名称
private Boolean active;//有效⽆效 true,false
private String activeString;//有效⽆效
private Boolean noSubscription;//是否需要订阅 true,false
private String noSubscriptionString;//是否需要订阅
private Long quantity;//数据量
private String _id;
private String ids;
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getActiveString() {
return activeString;
}
public void setActiveString(String activeString) {
this.activeString = activeString;
}
public Boolean getNoSubscription() {
return noSubscription;
}
public void setNoSubscription(Boolean noSubscription) {
}
public String getNoSubscriptionString() {
return noSubscriptionString;
}
public void setNoSubscriptionString(String noSubscriptionString) {
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
}
三、后台service层代码
public KnowledgeTopicListDTO selectTopicByName(String name, Integer page, Integer limit) {
SearchResponse searchResponse=null;
Map<String,Object> map = new HashMap<>();
TransportClient transportClient = ESClientConnection();
SearchRequestBuilder requestBuilder = client.prepareSearch("knowledge").setTypes("knowledge_theme");
// 声明where条件
BoolQueryBuilder qbs = QueryBuilders.boolQuery();
/**此处使⽤模糊匹配查询类⽐数据库中 like*/
QueryBuilder qb1 = QueryBuilders.matchPhraseQuery("name", name);
BoolQueryBuilder bqb1 = QueryBuilders.boolQuery().must(qb1);
qbs.must(bqb1);
requestBuilder.setQuery(qbs);
int num=limit*(page-1);
SearchResponse response = requestBuilder.setFrom(0).setSize(10).execute().actionGet();
//获取总条数
// long totalCount = Hits().getTotalHits();
List<KnowledgeTopicDTO> list = new ArrayList<KnowledgeTopicDTO>();
for (SearchHit hit : Hits().getHits()) {
//获取到当前页的数据
JSONObject obj = new JSONObject().SourceAsString());//将json字符串转换为json对象
KnowledgeTopicDTO topic = (KnowledgeTopicDTO) Bean(obj, KnowledgeTopicDTO.class);//将建json对象转换为Person对象 list.add(topic);
}
//查询主题总数
Terms terms= ESGroupByUtil.GroupByOne(client,"hottopic","hot","sum","tasktitleid");
list= groupList(list,terms);//调⽤组合主题总数⽅法
KnowledgeTopicListDTO knowledgeTopicListDTO = new KnowledgeTopicListDTO();
knowledgeTopicListDTO.setLimit(limit);
knowledgeTopicListDTO.setPage(page);
knowledgeTopicListDTO.setTopicDTOList(list);
return knowledgeTopicListDTO;
}
五、根据单个字段分组查询
public class ESGroupByUtil {
/**
*@description: 根据单个字段分组求和
*@author:cyb
*@date: 2018-11-16 17:31
*@param: client ES连接
*@param: indices 索引
*@param: types 类型
*@param: alias 分组求和别名
*@param: DomName 分组⽬标字段名
*@return: org.elasticsearch.search.s.Terms
*/
public static Terms GroupByOne(TransportClient client,String indices,String types,String alias,String DomName){
SearchRequestBuilder sbuilder = client.prepareSearch(indices).setTypes(types);
TermsAggregationBuilder termsBuilder = s(alias).field(DomName);
sbuilder.addAggregation(termsBuilder);
SearchResponse responses= ute().actionGet();
Terms terms = Aggregations().get(alias);
return terms;
}
}
六、将分组查询的数据进⾏整合到已查询到的集合中
/**
*@description:将查询的总数合并到list中
*@author:cyb
*@date: 2018-11-16 17:51
*@param: list
*@param: terms
*@return: java.util.List<com.yjlc.platform.bsKnowledge.KnowledgeTopicDTO>
*/
public List<KnowledgeTopicDTO> groupList(List<KnowledgeTopicDTO> list,Terms terms){
List<BsKnowledgeInfoDTO> lists = new ArrayList<>();
drop table if exists adminfor(int i=0;i&Buckets().size();i++){
//statistics
String id =Buckets().get(i).getKey().toString();//id
Long sum =Buckets().get(i).getDocCount();//数量
BsKnowledgeInfoDTO bsKnowledgeInfoDTO1 = new BsKnowledgeInfoDTO();
bsKnowledgeInfoDTO1.setId(id);
bsKnowledgeInfoDTO1.setSum(sum);
lists.add(bsKnowledgeInfoDTO1);
System.out.println("=="+ Buckets().get(i).getDocCount()+"------"+Buckets().get(i).getKey());
}
for(int i=0;i<lists.size();i++){
for(int j=0;j<list.size();j++){
(i).getId().(j).getId())){
<(j).(i).getSum());
}
}
}
return list;
}
总结:以上代码是本⼈的亲⾃测试通过的,分页后期建议⼤家不⽤使⽤from,size格式,当数据量超过1w的时候,速度会越来越慢,并可能造成宕机。
精准条件查询
MatchPhraseQueryBuilder mpq1 = QueryBuilders
.matchPhraseQuery("id",knowledgeId);
qbs.must(mpq1);//主题id
模糊条件查询
QueryBuilder qb1 = QueryBuilders.matchPhraseQuery("title", keyword);
qbs.must(qb1);
requestBuilder.setQuery(qbs);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论