码迷,mamicode.com
首页 > 其他好文 > 详细

solr4使用solrj操作索引库

时间:2014-12-20 15:31:55      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

solr配套有好多的客户端用于操作索引库,下面我们来讲如何用solrj去操作solr索引库。

一、认识solrj

solrj是solr的java客户端,用于访问solr索引库。它提供了添加、删除、查询、优化等功能。

二、下载

          百度、google以下solrj下载,你会发现根本就没有,那么我们该到哪儿下载呢?其实,它是集成到solr压缩包里的,解压文件后,有个目录/dist/solrj-lib,里面就存放了solrj所用到的jar,你把这些jar都添加到你的classpath就ok。

如果你是使用Maven来构建项目,添加以下代码到你的pom.xml配置文件中:

<dependency> 
        <artifactId>solr-solrj</artifactId> 
        <groupId>org.apache.solr</groupId> 
        <version>1.4.0</version> 
        <type>jar</type>
        <scope>compile</scope> 
</dependency>
<dependency> 
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.5.6</version> 
</dependency>

下面是具体使用Solr4j的工具类

 

package x.y.z;

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

import my.VirtualProxy;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import x.y.z.framework.search.vo.Content;
import x.y.z.framework.search.vo.Search;

//@Repository & @Autowired is use spring annotations
@Repository
public class SearchDAOImpl implements SearchDAO
{
    private static Logger logger = Logger.getLogger(SearchDAOImpl.class);
    
    //@Autowired
    private HttpSolrServer solrServer;
    
    @Override
    public void init()
    {
        // TODO Auto-generated method stub
        String SearchService_Url = "http://localhost:8983/solr";
        
        this.solrServer = new HttpSolrServer(SearchService_Url);
        try
        {
            solrServer.ping();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    @Override
    public void init(String url)
    {
        // TODO Auto-generated method stub
        this.solrServer = new HttpSolrServer(url);
        try
        {
            solrServer.ping();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    @Override
    public boolean ping()
    {
        // TODO Auto-generated method stub
        try
        {
            if(this.solrServer != null)
            {
                this.solrServer.ping();
                return true;
            }
            else
            {
                logger.debug("Manipulate null object.SolrServer must init.");
                return false;
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void addIndex(Content add)
    {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void deleteIndex(Content delete)
    {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void changeIndex(Content old_index, Content new_index)
    {
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public Search query(String query, int start, int rows,String SortField, boolean Highlight)
    {
        // TODO Auto-generated method stub
        if(this.solrServer != null)
        {
            SolrQuery solrQuery = new SolrQuery();
            solrQuery.setQuery(query);

            //start the query and show the rows number
            solrQuery.setStart(start);
            solrQuery.setRows(rows);
            
            //Sequence 
            //Sequence for the asscet time and Weights for the sort result
            //the seq must not a null value 
            solrQuery.addSortField(SortField, SolrQuery.ORDER.asc);
            
            //high light 
            solrQuery.setHighlight(true);
            solrQuery.addHighlightField("name");
            solrQuery.addHighlightField("id");
            solrQuery.addHighlightField("title");
            solrQuery.addHighlightField("features");
            solrQuery.addHighlightField("content");
            
            solrQuery.setHighlightSimplePre("<font color=‘red‘>");
            solrQuery.setHighlightSimplePost("</font>");

            solrQuery.setHighlightSnippets(1);//结果分片数,默认为1
            solrQuery.setHighlightFragsize(1000);//每个分片的最大长度,默认为100
            
            solrQuery.setFacet(true).setFacetMinCount(1).setFacetLimit(5).addFacetField("id").addFacetField("inStock");
            solrQuery.setFacet(true).setFacetMinCount(1).setFacetLimit(5).addFacetField("content").addFacetField("inStock");
            
            QueryResponse queryResponse = null;
            try
            {
                queryResponse = solrServer.query(solrQuery);
                SolrDocumentList solrDocumentList = queryResponse.getResults();

                return new Search(queryResponse,solrDocumentList);
            }
            catch (SolrServerException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        else
        {
            logger.debug("The Search Server is null value.");
        }
        return null;
    }

    @Override
    public void close()
    {
        // TODO Auto-generated method stub
        if(this.solrServer != null)
        {
            this.solrServer.shutdown();
        }
        else
        {
            logger.debug("Manipulate null object.SolrServer must init.");
        }
    }



    @Override
    public List<Content> queryAll()
    {
        // TODO Auto-generated method stub
        List<Content> list = new ArrayList<Content> ();
        
        if(this.solrServer != null)
        {
            
            SolrQuery solrQuery = new SolrQuery();
            //String query = "GB";
            String query = "*:*";
            solrQuery.setQuery(query);
            
            //add the 
            Integer start = 0;
            Integer rows  = 20;
            solrQuery.setStart(start);
            solrQuery.setRows(rows);
            
            //Sequence 
            //Sequence for the asscet time and Weights for the sort result
            //the seq must not a null value 
            //solrQuery.addSortField("name", SolrQuery.ORDER.asc);
            solrQuery.addSortField("id", SolrQuery.ORDER.asc);
            
            //high light 
            solrQuery.setHighlight(true);
            solrQuery.addHighlightField("name");
            solrQuery.addHighlightField("id");
            solrQuery.addHighlightField("title");
            solrQuery.addHighlightField("features");
            solrQuery.addHighlightField("content");
            
            solrQuery.setParam("hl.fl", "content");
            
            solrQuery.setHighlightSimplePre("<font color=\"red\">");
            solrQuery.setHighlightSimplePost("</font>");
            
            solrQuery.setFacet(true).setFacetMinCount(1).setFacetLimit(5).addFacetField("id");
            solrQuery.setFacet(true).setFacetMinCount(1).setFacetLimit(5).addFacetField("content");
            solrQuery.setFacet(true).setFacetMinCount(1).setFacetLimit(5).addFacetField("features");
            
            try
            {
                QueryResponse queryResponse = solrServer.query(solrQuery);
                SolrDocumentList docs = queryResponse.getResults();
                
                System.out.println("doc number found :" + docs.getNumFound());
                System.out.println("doc max score :" + docs.getMaxScore());
                
                for(SolrDocument doc : docs)
                {
                    String name = (String) doc.getFieldValue("name");  
                    String id = (String) doc.getFieldValue("id");  
                    ArrayList features = (ArrayList)doc.getFieldValue("features");
                    
                    //to add the list value must use the temp object
                    Content vo = new Content();
                    
                    //Set the vo object
                    vo.setId(id);
                    vo.setName(name);
                    vo.setFeatures(features);
                    
                    list.add(vo);
                    
                    //Print the list value
                    System.out.println("id        :" + id);  
                    System.out.println("name        :" + name);  
                    if(features != null)
                    {
                        for(Object feature : features.toArray())
                        {
                            System.out.println("feature        :" + feature.toString());
                        }
                    }
                }
            }
            catch (SolrServerException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {
            logger.debug("The Search Server is null value.");
        }
        return list;
    }

    @Override
    public int queryTotal(String query)
    {
        // TODO Auto-generated method stub
        if(this.solrServer != null)
        {
            
            SolrQuery solrQuery = new SolrQuery();
            solrQuery.setQuery(query);
            QueryResponse queryResponse;
            try
            {
                queryResponse = solrServer.query(solrQuery);
                return queryResponse.getResults().size();
            }
            catch (SolrServerException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return 0;
    }

    /*
     * (non-Javadoc)
     * @Warning it will clear ALL the index
     * @see com.cfp.framework.search.dao.SearchDAO#clearAll()
     */
    @Override
    public void clearAll()
    {
        // TODO Auto-generated method stub
        try
        {
            solrServer.deleteByQuery("*:*");
            solrServer.commit();
        }
        catch (SolrServerException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

solr4使用solrj操作索引库

标签:

原文地址:http://www.cnblogs.com/studies/p/4175438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!