solr简单应用的代码例子

来源:互联网 发布:淘宝购物几天能到货 编辑:程序博客网 时间:2024/05/18 02:08
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;

public class TestSolr
{

    private static HttpSolrServer server = new HttpSolrServer("http://192.168.91.76:8080/solr/core0");
    
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        //deleteAll();
        
        //add();
        
        //spellcheck("name:劳斯莱斯保时捷", true);
        
        // 冒号是模糊查询,会分词
        // 等号是精确查询,不分词
        // && 并且
        // || 或者
        //search("name:劳斯莱斯保时捷");
        //search("name=原来是美男啊 - 第1集 && name:原来是美男啊 - 第1集");
        
        analysis("劳斯莱斯保时捷六婶");
    }
    
    public static void delete(String id)
    {
        try
        {
            server.deleteById(id);// 直接根据ID删除 server.deleteByQuery("*:*");删除所有
            server.commit();
        }
        catch (SolrServerException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 删除
     */
    public static void deleteAll()
    {
        try
        {
            server.deleteByQuery("*:*");
            server.commit();
        }
        catch (SolrServerException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 添加
     */
    public static void add()
    {
        try
        {
            for (int i = 0; i < 2; ++i)
            {
                SolrInputDocument doc = new SolrInputDocument();
                doc.addField("type", "test " + i);
                //doc.addField("id", "test book-" + i);
                doc.addField("name", "阿莱克斯" + i);
                server.add(doc);
                if (i % 5 == 0)
                {
                    server.commit();
                }
            }
            server.commit();

            System.out.println("Success.");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public static void analysis(String string)
    {
        HttpClient httpClient = server.getHttpClient();
        
        String url = "http://192.168.91.76:8080/solr/core0/analysis/field?analysis.fieldtype=text_ik&indent=on&wt=json&q=" + string;        
        HttpGet httpMethod = new HttpGet(url);

        try
        {
            HttpResponse response = httpClient.execute(httpMethod);
            
            String result = EntityUtils.toString(response.getEntity());
            
            System.out.println(result);
        }
        catch (ClientProtocolException e)
        {
            System.out.println(e.toString());
        }
        catch (IOException e)
        {
            System.out.println(e.toString());
        }
    }

    /**
     * 查询
     * @param q
     */
    public static void search(String q)
    {
        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set("q", q);
        params.set("defType", "edismax");
        params.set("start", "0");

        QueryResponse response = null;
        try
        {
            response = server.query(params);
        }
        catch (SolrServerException e)
        {
            System.out.println(e.toString());
        }
        SolrDocumentList results = response.getResults();
        for (int i = 0; i < results.size(); ++i)
        {
            System.out.println(results.get(i));
        }
    }
    
    /**
     * 拼写校验,联想查询
     * @param token
     */
    public static void spellcheck(String token, boolean rebuild)
    {
        SolrQuery params = new SolrQuery();
        params.set("qt", "/search");
        params.set("q", token);
        
        if (rebuild)
        {
            params.set("spellcheck.build", true);
            params.set("spellcheck.reload", true);
        }
        
        QueryResponse response = null;

        try
        {
            response = server.query(params);
            System.out.println("查询耗时:" + response.getQTime());
        }
        catch (SolrServerException e)
        {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }

        SpellCheckResponse spellCheckResponse = response.getSpellCheckResponse();
        if (spellCheckResponse != null)
        {
            List<Suggestion> suggestionList = spellCheckResponse.getSuggestions();
            for (Suggestion suggestion : suggestionList)
            {
                System.out.println("Suggestions NumFound: " + suggestion.getNumFound());
                System.out.println("Token: " + suggestion.getToken());
                System.out.print("Suggested: ");
                List<String> suggestedWordList = suggestion.getAlternatives();
                for (String word : suggestedWordList)
                {
                    System.out.println(word + ", ");
                    search("name:" + word);
                }
                System.out.println();
            }
        }
    }
}


0 0