package com.taotao.rest.solr; import java.io.IOException; 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; import org.apache.solr.common.SolrInputDocument; import org.junit.Test; public class SolrJTest { @Test public void addDocument() throws SolrServerException, IOException { //创建一个连接 HttpSolrServer solrServer = new HttpSolrServer("http://192.168.29.102:8080/solr"); //创建一个文档对象 SolrInputDocument document = new SolrInputDocument(); document.addField("id", "test009"); document.addField("item_title", "测试商品9"); document.addField("item_price", 12999); //把文档对象写入数据库 solrServer.add(document); //提交 solrServer.commit(); } @Test public void deleteDocument() throws Exception { //创建一个连接 HttpSolrServer solrServer = new HttpSolrServer("http://192.168.29.102:8080/solr"); //删除 // solrServer.deleteById("test002"); solrServer.deleteByQuery("*:*"); //提交 solrServer.commit(); } @Test public void queryDocument() throws Exception { //创建连接 SolrServer solrServer = new HttpSolrServer("http://192.168.29.102:8080/solr"); //创建一个查询对象 SolrQuery query = new SolrQuery(); //设置查询条件 query.setQuery("*:*"); //下面这两个即使不设置也会有默认值 query.setStart(20); query.setRows(50); //执行查询 QueryResponse response = solrServer.query(query); //取查询结果 SolrDocumentList solrDocumentList = response.getResults(); for (SolrDocument document : solrDocumentList) { System.err.println(document.get("id")); System.err.println(document.get("item_title")); System.err.println(document.get("item_price")); System.err.println(document.get("item_image")); } } }