首页 > 代码库 > SolrJ简单使用

SolrJ简单使用

最近在电脑上简单的安装了一下Solr并简单的使用了SolrJ进行查询,下面是我的程序。

import java.io.IOException;import java.net.URISyntaxException;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.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;public class SolrImpl {        private SolrServer server;        public SolrImpl(String indexHost) throws URISyntaxException {        this.server = new HttpSolrServer(indexHost);    }        /**     * 查询     * @param q     * @param pageNow     * @return     * @throws SolrServerException     */        public QueryResponse queryDocuments(String q, int pageNow,int countPerPage)            throws SolrServerException {                 SolrQuery query = new SolrQuery();                query.setRequestHandler("/select");        //q=escapeQueryChars(q);        query.set("q",q);  //要检索字段由df制定,默认为copyfield text{title,html}        System.err.println(q);        // 分页        query.setRows(countPerPage);// 每次取多少条        query.setStart(pageNow);// 从第几条开始查询                //所有配置已经移入配置文件        // 高亮现实        //query.set("fl","*");        query.setHighlight(true); // 开启高亮组件        query.addHighlightField("TEXT");// 高亮字段        //query.addHighlightField("title");        //query.setHighlightSimplePre("");// 标记        //query.setHighlightSimplePost("");        //query.set("hl.usePhraseHighlighter", true);        //query.set("hl.highlightMultiTerm", true);        query.setHighlightSnippets(100);// 结果分片数,默认为 1        query.setHighlightFragsize(1);// 每个分片的最大长度        QueryResponse response = server.query(query);        return response;    }    /**     * 将查询中的特殊字符进行转义处理     *      * @param s     * @return s     */    public static String escapeQueryChars(String s) {        StringBuilder sb = new StringBuilder();        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            // These characters are part of the query syntax and must be escaped            if (c == ‘\\‘ || c == ‘+‘ || c == ‘-‘ || c == ‘!‘ || c == ‘(‘                    || c == ‘)‘ || c == ‘:‘ || c == ‘^‘ || c == ‘[‘ || c == ‘]‘                    || c == ‘{‘ || c == ‘}‘ || c == ‘~‘                    || c == ‘*‘ || c == ‘?‘ || c == ‘|‘ || c == ‘&‘ || c == ‘;‘                    || c == ‘/‘)            {                sb.append(‘\\‘);            }            sb.append(c);        }        String q = sb.toString();        q = q.replaceAll("“","\"");   //中文引号替换        q = q.replaceAll("”","\"");   //中文引号替换        q = q.toUpperCase();  //逻辑符号转换成大写        return q;    }    /**     * 按id查询获得快照     * @param id     * @return     * @throws SolrServerException     */    public String getSnap(String id) throws SolrServerException {        SolrQuery query = new SolrQuery();        id=escapeQueryChars(id);        query.set("q", "id:" + id);        QueryResponse response = server.query(query);        String html = (String)response.getResults().get(0).getFieldValue("html");        return html;    }        //删除所用索引    public void deleteAllIndex() throws SolrServerException, IOException{          server.deleteByQuery("*:*");          server.commit();            }    /**     * 建立全文索引     */    public  void fullIndex()    {        SolrQuery query = new SolrQuery();        // 指定RequestHandler,默认使用/select        query.setRequestHandler("/dataimport");                query.setParam("command", "full-import")             .setParam("clean", "true")             .setParam("commit", "true")             .setParam("optimize", "true");             //.setParam("entity", "spider_data")        try         {            this.server.query(query);        } catch (SolrServerException e)         {            e.printStackTrace();            System.out.println("建立全文索引失败!");        }    }    /**     * 建立增量索引     */    public void deltaIndex() {        SolrQuery query = new SolrQuery();        // 指定RequestHandler,默认使用/select        query.setRequestHandler("/dataimport");                query.setParam("command", "delta-import")             .setParam("clean", "false")             .setParam("commit", "true")             .setParam("optimize", "true");             //.setParam("entity", "spider_data")        try         {            this.server.query(query);        } catch (SolrServerException e)         {            e.printStackTrace();            System.out.println("增量索引建立失败!");        }    }        public static void main(String[] args) throws SolrServerException, URISyntaxException {        SolrImpl solrImpl = new SolrImpl("http://localhost:8080/solr/");         String q= "((\"gao\")OR(\"solr\"))NOT(\"yang\")";         //q=escapeQueryChars(q);         QueryResponse qr = solrImpl.queryDocuments(q,0,10);                  //Map<String, Map<String,List<String>>> highlight = qr.getHighlighting();         SolrDocumentList documentList=qr.getResults();         System.err.println(documentList.getNumFound());         for (SolrDocument solrDocument : documentList)         {                       System.out.println(solrDocument.getFieldValue("id"));             System.out.println(solrDocument.getFieldValue("name"));             System.out.println(solrDocument.getFieldValue("password"));            //System.out.println((String)solrDocument.getFieldValue("title"));            //String id = (String) solrDocument.getFieldValue("id");            //System.err.println(highlight.get(id).get("html").get(0));            /*             System.out.println((String)solrDocument.getFieldValue("content"));             System.out.println(solrDocument.getFieldValue("tstamp"));             System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(solrDocument.getFieldValue("tstamp")));             System.out.println((String)solrDocument.getFieldValue("html"));                     */         }    }}

以后准备做一个界面出来

SolrJ简单使用