<dependency> <artifactId>solr-solrj</artifactId> <groupId>org.apache.solr</groupId> <version>4.0.0</version> <type>jar</type> <scope>compile</scope> </dependency>
String url = "http://192.168.22.216:8983/solr"; HttpSolrServer server = new HttpSolrServer(url); server.setSoTimeout(3000); // socket read timeout server.setConnectionTimeout(1000); server.setDefaultMaxConnectionsPerHost(1000); server.setMaxTotalConnections(10); server.setFollowRedirects(false); // defaults to false server.setAllowCompression(true); server.setMaxRetries(1);
try { server.deleteByQuery("*:*"); } catch (SolrServerException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); }
//构造document1 SolrInputDocument doc1 = new SolrInputDocument(); doc1.addField( "id", "id1", 1.0f ); doc1.addField( "name", "doc1", 1.0f ); doc1.addField( "price", 10 ); //构造document2 SolrInputDocument doc2 = new SolrInputDocument(); doc2.addField( "id", "id2", 1.0f ); doc2.addField( "name", "doc2", 1.0f ); doc2.addField( "price", 20 ); //构造document集合 Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); docs.add(doc1); docs.add(doc2); //将documents提交给solr try { server.add(docs); } catch (SolrServerException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } //提交一个commit(方法一) try { server.commit(); } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
//设置查询条件 SolrQuery query = new SolrQuery(); query.setQuery("*:*"); query.addField("name"); query.setStart(0); query.setRows(4); query.addSortField("id", SolrQuery.ORDER.desc); //query.addSortField("auction_point", SolrQuery.ORDER.asc);
5 处理查询结果
//处理查询结果 QueryResponse qrsp = null; try { qrsp = server.query(query); } catch (SolrServerException e) { e.printStackTrace(); } SolrDocumentList docsT = qrsp.getResults(); Iterator i = docs.iterator(); while(i.hasNext()){ System.out.println(i.next()); }