Solrj是Solr官方提供的基于Java的Solr客户端,提供完善的Solr操作API。
以好友为例。首先定义SpaceFriend实体Bean,用来直接处理Solr返回信息:
import org.apache.solr.client.solrj.beans.Field;
public class SpaceFriend {
@Field("Id")
int id;
@Field("WebNickname")
String webNickname;
@Field("portrait")
String Portrait;
@Field("Gender")
int gender;
@Field("Age")
int age;
@Field("IsAgePublic")
boolean isAgePublic;
@Field("Horoscope")
int horoscope;
@Field("marriage")
int marriage;
@Field("FriendType")
String[] friendType;
@Field("CityNow")
String cityNow;
@Field("isCityPublic")
boolean isCityPublic;
}
为了方便写了一个junit测试:
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.impl.BinaryRequestWriter;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
public class SolrJTest {
//多线程共享
static CommonsHttpSolrServer server;
@BeforeClass
public static void beforeClassClass() throws Exception {
server = new CommonsHttpSolrServer(
"http://localhost:8088/solr");
server.setSoTimeout(1000);
server.setConnectionTimeout(100);
server.setDefaultMaxConnectionsPerHost(100);
server.setMaxTotalConnections(100);
server.setFollowRedirects(false);
server.setAllowCompression(true);
server.setMaxRetries(1);
//提升性能采用流输出方式
server.setRequestWriter(new BinaryRequestWriter());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
public void QueryTest() throws SolrServerException {
SolrQuery query = new SolrQuery();
//主查询
query.setQuery("*:*");
//采用过滤器查询可以提高性能
query.addFilterQuery("Searchable:1");
query.addFilterQuery("SpaceAccessPrivate:1");
//区间查询
query.addFilterQuery("Age:[* TO 50]");
query.addFilterQuery("FriendType:1");
//添加排序
query.addSortField("Score", ORDER.desc);
//分页返回结果
query.setStart(0);
query.setRows(10);
QueryResponse rsp = server.query(query);
List<SpaceFriend> beans = rsp.getBeans(SpaceFriend.class);
//输出符合条件的结果数
System.out.println("NumFound: " + rsp.getResults().getNumFound());
//输出结果
for (int i = 0; i < beans.size(); i++) {
SpaceFriend friend = beans.get(i);
System.out.println("SpaceFriend " + i);
System.out.println("Id " + friend.id);
System.out.println("WebNickname:" + friend.webNickname);
}
}
}