博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot+elasticsearch + rabbitMQ实现全文检索(使用transportClient 实现CRUD)
阅读量:6500 次
发布时间:2019-06-24

本文共 9257 字,大约阅读时间需要 30 分钟。

package com.mytian.service.impl;import com.alibaba.fastjson.JSONArray;import com.mytian.entity.BlogImgUrl;import com.mytian.entity.BlogInfo;import com.mytian.entity.SearchTermBean;import com.mytian.service.PublishBlogService;import com.mytian.service.SearchService;import com.mytian.util.MytBeanUtils;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.action.update.UpdateRequest;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.unit.Fuzziness;import org.elasticsearch.common.xcontent.XContentType;import org.elasticsearch.index.query.BoolQueryBuilder;import org.elasticsearch.index.query.MultiMatchQueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.rest.RestStatus;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.SearchHits;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import static jdk.nashorn.internal.objects.Global.println;import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;/** * 搜索服务 * * @author m.feng * @create 2018-12-14-17:50 */@RestControllerpublic class SearchServiceImpl implements SearchService {    public static Logger LOGGER = LoggerFactory.getLogger(SearchServiceImpl.class);    @Autowired    private TransportClient transportClient;    @Autowired    private PublishBlogService publishBlogService;    @Override    public boolean  saveBlogTitle(String json) throws Exception {        IndexResponse response = transportClient.prepareIndex("bloginfo", "blog")                .setSource(json, XContentType.JSON)                .get();        // 索引名字        String _index = response.getIndex();        // 类型        String _type = response.getType();        // 文档ID        String _id = response.getId();        // 文档版本号        long _version = response.getVersion();        RestStatus status = response.status();        System.out.println(_index+"_"+_type+"_"+_id);        return true;    }    @Override    public boolean addBlogInfo(@RequestBody BlogInfo blogInfo)throws IOException {        List
blogImgUrls = blogInfo.getBlogImgUrls(); String imgStr = JSONArray.toJSONString(blogImgUrls); IndexResponse response = transportClient.prepareIndex("bloginfo", "blog",blogInfo.getBlogId().toString()) .setSource(jsonBuilder() .startObject() .field("blogId", blogInfo.getBlogId()) .field("uid", blogInfo.getUid()) .field("title", blogInfo.getTitle()) .field("specialTopicId", blogInfo.getSpecialTopicId()) .field("updateTime", blogInfo.getUpdateTime()) .field("insertTime", blogInfo.getInsertTime()) .field("blogGrade", blogInfo.getBlogGrade()) .field("shareNum", blogInfo.getShareNum()) .field("agreeNum", blogInfo.getAgreeNum()) .field("commentNum", blogInfo.getCommentNum()) .field("status", blogInfo.getStatus()) .field("isSee", blogInfo.getIsSee()) .field("isReal", blogInfo.getIsReal()) .field("headThumb", blogInfo.getHeadThumb()) .field("alias", blogInfo.getAlias()) .field("blogContent", blogInfo.getBlogContent()) .field("blogImgUrls", imgStr) .endObject() ) .get(); return true; }// @Override// public String mymatchQuery() throws Exception{// QueryBuilder qb = QueryBuilders.matchQuery(// "title",//字段// "牧风"//搜索的文本// );// SearchResponse response = transportClient.prepareSearch("bloginfo").setQuery(qb).get();// //解析response// System.out.println(response);// SearchHits hits = response.getHits();// List
list = new ArrayList();// for (SearchHit searchHit : hits) {// Map source = searchHit.getSource();// BlogInfo blogInfo = new BlogInfo();// MytBeanUtils. transMap2Bean(source,blogInfo);// list.add(blogInfo);// }// String string = JSONArray.toJSONString(list);// System.out.println(string);// return string;// } @Override public String mymatchQuery(@RequestBody SearchTermBean searchTermBean,Integer uid) throws Exception{ String indexSea = searchTermBean.getIndexSea(); Integer page = searchTermBean.getPage(); String search = searchTermBean.getSearch(); Integer size = searchTermBean.getSize(); String typeSea = searchTermBean.getTypeSea(); LOGGER.info("-[全文检索条件]--[indexSea]-" + "-"+indexSea+"--[page]--"+page+"--[search]-" + "-"+search+"--[size]--"+size+"--[typeSea]--"+typeSea+"-----"); BoolQueryBuilder mustQuery = QueryBuilders.boolQuery(); MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(search,"title", "content"); mustQuery.must(QueryBuilders.matchAllQuery()); // 添加第1条must的条件 此处为匹配所有文档 mustQuery.must(QueryBuilders.matchPhraseQuery("status", 1)); mustQuery.must(QueryBuilders.matchPhraseQuery("isSee", 1)); mustQuery.must(QueryBuilders.matchPhraseQuery("isReal", 1)); mustQuery.must(multiMatchQueryBuilder); SearchResponse searchResponse = transportClient.prepareSearch() .setIndices(indexSea) .setTypes(typeSea) .setFrom(page).setSize(size) .setQuery(mustQuery) .execute() .actionGet(); List
list = new ArrayList(); SearchHits hits = searchResponse.getHits(); for (SearchHit searchHit : hits) { Map source = searchHit.getSource(); BlogInfo blogInfo = new BlogInfo(); MytBeanUtils. transMap2Bean(source,blogInfo); list.add(blogInfo); } for (BlogInfo blogInfo : list){ blogInfo.setIsAgree(0); if (uid != null){ Integer integer = publishBlogService.selectCountByUidAndBlogID(uid,blogInfo.getBlogId()); if (integer == 1){ blogInfo.setIsAgree(1); } } } String string = JSONArray.toJSONString(list); LOGGER.info("--------查询结果------"+string+"---------------"); return string; } @Override public void updateESBlog(@RequestBody BlogInfo blogInfo) throws Exception { UpdateRequest updateRequest = new UpdateRequest("bloginfo", "blog", blogInfo.getBlogId().toString()); updateRequest.doc(blogInfo); transportClient.update(updateRequest); }}

 

因为 我的bean 里面套了一个list 在将返回结果编程对象的时候失败了

package com.mytian.util;import com.alibaba.fastjson.JSONArray;import com.mytian.entity.BlogInfo;import java.beans.BeanInfo;import java.beans.IntrospectionException;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.List;import java.util.Map;/** * 麦田bean工具 * * @author m.feng * @create 2018-12-19-14:42 */public class MytBeanUtils {    /**     * 讲map转换 blogInfo 对象     * @param map     * @param obj     * @throws IntrospectionException     * @throws InvocationTargetException     * @throws IllegalAccessException     */    public static void transMap2Bean(Map
map, BlogInfo obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.equals("blogImgUrls")){ String value =(String) map.get(key);// String string = JSONObject.toJSONString(value); List list = JSONArray.parseObject(value, List.class); obj.setBlogImgUrls(list); continue;// ObjectMapper mapper = new ObjectMapper();// List
beanList = mapper.readValue(string, new TypeReference
>() {}); } if (map.containsKey(key)) { Object value = map.get(key); // 得到property对应的setter方法 Method setter = property.getWriteMethod(); setter.invoke(obj, value); } } }}

我自己单独处理了一下 解决com.fasterxml.jackson.databind.JsonMappingException: No suitable 以 Jackson

 

 

引用博文:

 多条件组合查询

 Multi Match Query实现查询

 这个对我帮助很大

 

分页

转载于:https://www.cnblogs.com/mfser/p/10150088.html

你可能感兴趣的文章
跨链技术与通证经济
查看>>
爬虫学习之-xpath
查看>>
js jQuery 右键菜单 清屏
查看>>
dotConnect for Oracle
查看>>
Eclipse下C/C++开发环境搭建
查看>>
Eclipse中设置在创建新类时自动生成注释
查看>>
我的友情链接
查看>>
CoreOS 手动更新
查看>>
golang 分页
查看>>
再论机械式针对接口编程
查看>>
25 个 Linux 性能监控工具
查看>>
C#程序员整理的Unity 3D笔记(十三):Unity 3D基于组件的思想
查看>>
Tengine-2.1.1 ngx_http_concat_module 400问题
查看>>
Windows中挂载安装ISO文件
查看>>
Wayland 1.0发布
查看>>
golang的goroutine是如何实现的?
查看>>
乐视云基于Kubernetes的PaaS平台建设
查看>>
R 学习笔记《十》 R语言初学者指南--图形工具
查看>>
PHP通过读取DOM抓取信息
查看>>
DICOM医学图像处理:DICOM网络传输
查看>>