Eclipse使用solrJ 7.7.0连接solr步骤
先写一个测试类:
1 package com.taotao.rest.solrj; 2 3 import org.apache.solr.client.solrj.SolrClient; 4 import org.apache.solr.client.solrj.impl.HttpSolrClient; 5 import org.apache.solr.common.SolrInputDocument; 6 import org.junit.Test; 7 8 public class SolrJTest { 9 10 public static final String BASE_URL = "http://192.168.83.133:8080/solr/collection1"; 11 @Test 12 public void addDocument() throws Exception { 13 //创建一个连接 14 SolrClient solrClient = new HttpSolrClient.Builder(BASE_URL).withConnectionTimeout(1000).withSocketTimeout(6000).build(); 15 //创建一个文档对象 16 SolrInputDocument document = new SolrInputDocument(); 17 document.addField("id", "test001"); 18 document.addField("item_title", "测试商品2"); 19 document.addField("item_price", 123456); 20 //把文档对象写入索引库 21 solrClient.add(document); 22 //提交 23 solrClient.commit(); 24 } 25 26 @Test 27 public void delete() throws Exception{ 28 // 创建一个连接 29 SolrClient solrClient = new HttpSolrClient.Builder(BASE_URL).withConnectionTimeout(1000).withSocketTimeout(6000).build(); 30 //solrClient.deleteById("test001"); 31 solrClient.deleteByQuery("*:*"); 32 solrClient.commit(); 33 } 34 }
说明:最新版的jar包中已经没有SolrServer这个类了,取而代之的是SolrClient。
通过URL操作Solr:
resource.properties:
1 #solr服务地址 2 SOLR.SERVER.URL=http://192.168.83.133:8080/solr/collection1
spring 中的 applicationContext-solr.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 9 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 10 11 <!-- 配置SolrServer对象 --> 12 <!-- 单机版 --> 13 <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrClient"> 14 <constructor-arg name="builder" value="${SOLR.SERVER.URL}"></constructor-arg> 15 </bean> 16 </beans>
说明:使用时注意版本。