Solr6.3 在Java中的简单使用

 
  
import com.backzero.solr.service.SolrService;
import com.backzero.solr.util.SolrUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by BackZero on 2016/11/29 0029.
 */
@Service
@Transactional
public class SolerServiceImpl implements SolrService {

    /**
     * 简单查询
     * @param mQueryStr
     * @return query result
     */
    public SolrDocumentList query(String mQueryStr) {

        try {
            HttpSolrClient httpSolrClient = SolrUtils.connect();
            SolrQuery query = new SolrQuery();
            //设定查询字段
            query.setQuery(mQueryStr);
            //指定返回结果字段
            query.set("fl","id,name");
            //覆盖schema.xml的defaultOperator(有空格时用"AND"还是用"OR"操作逻辑),一般默认指定。必须大写
            query.set("q.op","AND");
            //设定返回记录数,默认为10条
            query.setRows(10);
            QueryResponse response = httpSolrClient.query(query);
            SolrDocumentList list = response.getResults();
            return  list;
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页查询
     * @param queryStr
     * @param start
     * @param rows
     * @return SolrDocumentList
     */
    public SolrDocumentList queryPage(String queryStr,Integer start,Integer rows ){
        try {
            HttpSolrClient httpSolrClient = SolrUtils.connect();
            SolrQuery query = new SolrQuery();
            //设定查询字段
            query.setQuery(queryStr);
            //指定返回结果字段
            query.setIncludeScore(true);
            // query.set("fl","id,name");
            //覆盖schema.xml的defaultOperator(有空格时用"AND"还是用"OR"操作逻辑),一般默认指定。必须大写
            query.set("q.op","AND");
            //分页开始页数
            query.setStart(start);
            //设定返回记录数,默认为10条
            query.setRows(rows);
            //设定对查询结果是否高亮
            query.setHighlight(true);
            //设定高亮字段前置标签
            query.setHighlightSimplePre("");
            //设定高亮字段后置标签
            query.setHighlightSimplePost("");
            //设定高亮字段
            query.addHighlightField("name");
            //设定拼写检查
            query.setRequestHandler("/spell");
            QueryResponse response = httpSolrClient.query(query);
           //获取bean
           //  List bean = response.getBeans(Object.class);
            SolrDocumentList list = response.getResults();
            return  list;
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 添加一个实体
     *
     * @param object
     */
    public void addBean(Object object) {
        try {
            HttpSolrClient httpSolrClient = SolrUtils.connect();
            httpSolrClient.addBean(object);
            httpSolrClient.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加简单索引
     *
     * @param map
     */
    public void addDoc(Map map) {
        try {
            HttpSolrClient httpSolrClient = SolrUtils.connect();
            SolrInputDocument document = new SolrInputDocument();
            document = SolrUtils.addFileds(map,document);
            UpdateResponse response = httpSolrClient.add(document);
            httpSolrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除索引
     *
     * @param id
     */
    public void deleteById(String id) {
        try {
            HttpSolrClient httpSolrClient = SolrUtils.connect();
            httpSolrClient.deleteById(id);
            httpSolrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
 
  

import java.lang.reflect.Field;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.LoggerFactory;
import org.apache.commons.beanutils.BeanUtils;


import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;

/**
 * solr 工具类
 * Created by BackZero on 2016/11/29 0029.
 */
public class SolrUtils {

    /**
     * solr 服务器访问地址
     */
    private static String url = "http://localhost:9090/solr/new_core";

    private static Integer connectionTimeout = 100; // socket read timeout

    private static Integer defaltMaxConnectionsPerHost = 100 ;

    private static Integer maxTotalConnections = 100 ;

    private static Boolean  followRedirects = false ; // defaults to false
    private static Boolean allowCompression = true ;

   // private static  Integer maxRetries = 1 ; //defaults to 0.  > 1 not recommended.

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SolrUtils.class);

    /**
     * @param map key is filed name value,map value is filed value
     * @return SolrInputDocument
     */
    public static SolrInputDocument addFileds(Map map, SolrInputDocument document){

        if(document == null){
            document = new SolrInputDocument();
        }
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next().toString();
            document.setField(key,map.get(key));
        }
        return document;
    }

    /**
     *建立solr链接,获取 HttpSolrClient
     * @return HttpSolrClient
     */
    public static HttpSolrClient connect(){

        HttpSolrClient httpSolrClient = null;
        try{
            httpSolrClient = new HttpSolrClient.Builder(url).build();
            httpSolrClient.setParser(new XMLResponseParser());//设定xml文档解析器
            httpSolrClient.setConnectionTimeout(connectionTimeout);//socket read timeout
            httpSolrClient.setAllowCompression(allowCompression);
            httpSolrClient.setMaxTotalConnections(maxTotalConnections);
            httpSolrClient.setDefaultMaxConnectionsPerHost(defaltMaxConnectionsPerHost);
            httpSolrClient.setFollowRedirects(followRedirects);
        }catch (SolrException e){
            System.out.println("请检查tomcat服务器或端口是否开启!");
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return  httpSolrClient;
    }

    /**
     * 将SolrDocument 转换为Bean
     * @param record
     * @param clazz
     * @return bean
     */
    public static Object toBean(SolrDocument record, Class clazz){
        Object obj = null;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields){
            Object value = record.get(field.getName());
            try {
                BeanUtils.setProperty(obj, field.getName(), value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
}

}

你可能感兴趣的:(Solr6.3 在Java中的简单使用)