springboot+elasticsearch + rabbitMQ实现全文检索(使用transportClient 实现CRUD)

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
 */
@RestController
public 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

https://blog.csdn.net/yinjayhui123/article/details/45196843

 

 

引用博文:https://www.cnblogs.com/ghj1976/p/5293250.html

http://www.cnblogs.com/fclbky/p/7124469.html

https://www.cnblogs.com/wpcnblog/p/7903716.html

https://blog.csdn.net/hu582205/article/details/84861619

https://blog.csdn.net/dm_vincent/article/details/41800351

https://blog.csdn.net/lom9357bye/article/details/52852533

https://www.cnblogs.com/sbj-dawn/p/8891419.html

https://blog.csdn.net/g1969119894/article/details/80169055

https://blog.csdn.net/alan_liuyue/article/details/78588901 多条件组合查询

https://blog.csdn.net/qq_36330643/article/details/79071737 Multi Match Query实现查询

https://blog.csdn.net/u011781521/article/details/77848489 这个对我帮助很大

 

分页

https://blog.csdn.net/u013514928/article/details/78749419

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

你可能感兴趣的:(springboot+elasticsearch + rabbitMQ实现全文检索(使用transportClient 实现CRUD))