对solr服务的基本操作

前提是您已经能在Tomcat中部署Solr

 

1.PostTool.Java

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class PostTool {
   
    public void postData(URL solrUrl, Reader data, Writer output) {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) solrUrl.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (Exception e) {

            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=utf-8");

            OutputStream out = urlc.getOutputStream();

            try {
                Writer writer = new OutputStreamWriter(out, "utf-8");
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {

            } finally {
                if(out!=null) out.close();
            }

            InputStream in = urlc.getInputStream();
           
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException e) {

            } finally {
                if(in!=null) in.close();
            }

        } catch (IOException e) {


        } finally {
            if(urlc!=null) urlc.disconnect();
        }
    }
   
    private static void pipe(Reader reader, Writer writer) throws IOException {
        char[] buf = new char[1024];
        int read = 0;
        while((read = reader.read(buf) ) >= 0) {
            writer.write(buf, 0, read);
        }
       
        writer.flush();
    }
   
    //
    public Document postData(String solrUrl) {
        Document document = null;
        try {
            URL url = new URL(solrUrl);
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("Content-type", "text/xml; charset=utf-8");
            urlc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "utf-8"));
            SAXReader reader = new SAXReader();
            document = reader.read(in);
           
            in.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
       
        return document;
    }
   
    //用于增加
    public void postData(String solrUrl, Document document) {
        try {
            URL url = new URL(solrUrl);
            ByteArrayInputStream stream = new ByteArrayInputStream(document.asXML().getBytes("utf-8"));
            final StringWriter sw = new StringWriter();
            postData(url, new InputStreamReader(stream,"utf-8"), sw);
            postData(url, new StringReader("<commit/>"), sw);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
   
}

 

2.SolrTest.Java

import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * solr操作
 * @author Rain
 */
public class SolrTest {
   
    public static String serverURL = "http://localhost:8080";
   
    /**
     * 查询,结果返回xml文档
     * url=http://localhost:8080/solr/select/?version=2.2&start=0&rows=10&indent=on&q=xm_s:测试
     * @param keyWord
     * @return Document
     */
    public Document select(String keyWord) {
        try {
            keyWord = URLEncoder.encode(keyWord, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String solrUrl = serverURL + "/solr/select/?version=2.2&start=0&rows=10&indent=on&q=xm_s:" + keyWord;
        return new PostTool().postData(solrUrl);
    }
   
    /**
     * 增加
     * url=http://localhost:8080/solr/update
     * @param xm 姓名
     * @param sfzhm 身份证
     */
    public void addDoc(String xm, String sfzhm) {
        String solrUrl = serverURL + "/solr/update";
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("add");
        Element doc = root.addElement("doc");
        Element field = null;

        field = doc.addElement("field");
        field.addAttribute("name", "id");
        field.addText(String.valueOf(System.currentTimeMillis()));

        field = doc.addElement("field");
        field.addAttribute("name", "xm_s");
        field.addText(xm);
       
        field = doc.addElement("field");
        field.addAttribute("name", "sfzhm_s");
        field.addText(sfzhm);
       
        new PostTool().postData(solrUrl, document);
    }
   
    /**
     * 修改(通过id修改)
     * @param id id
     * @param xm 姓名
     * @param sfzhm 身份证
     */
    public void update(String id, String xm, String sfzhm) {
        String solrUrl = serverURL + "/solr/update";
       
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("add");
        Element doc = root.addElement("doc");
        Element field = null;

        field = doc.addElement("field");
        field.addAttribute("name", "id");
        field.addText(id);

        field = doc.addElement("field");
        field.addAttribute("name", "xm_s");
        field.addText(xm);
       
        field = doc.addElement("field");
        field.addAttribute("name", "sfzhm_s");
        field.addText(sfzhm);
       
        new PostTool().postData(solrUrl, document);
    }
   
    /**
     * 删除
     * url=http://localhost:8080/solr/update
     * @param id id
     */
    public void delete(String id) {
        String solrUrl = serverURL + "/solr/update";
        try {
            URL url = new URL(solrUrl);
           
            final StringWriter sw = new StringWriter();
            PostTool postTool = new PostTool();
            postTool.postData(url, new StringReader("<delete><id>"+id+"</id></delete>"),sw);
            postTool.postData(url, new StringReader("<commit/>"), sw);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
   
    /**
     * 当前日期字符
     * @return String 日期字符
     */
    public static String getCurrentDateTime(String type) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        String dateString = sdf.format(new Date());

        return dateString;
    }
   
    public static void main(String[] args) {
        SolrTest solrTest = new SolrTest();
       
        solrTest.addDoc("测试", "123456789");
        solrTest.addDoc("某人", "888888888");
        Document d = solrTest.select("测试");
        System.out.println(d.asXML());
       
        solrTest.update("1212547585639", "郁闷", "77777777777");
        //Document d = solrTest.select("郁闷");
        //System.out.println(d.asXML());
       
        solrTest.delete("1212547585639");
        //Document d = solrTest.select("郁闷");
        //System.out.println(d.asXML());
    }

}

你可能感兴趣的:(java,tomcat,.net,xml,Solr)