Solr语法解析及SolrJ使用
标签(空格分隔): Solr
官方指南:http://lucene.apache.org/solr/quickstart.html
Solrj 之HttpSolrClient
旧版本的连接服务HttpSolrServer在solr5版本后已经停用,被新的HttpSolrClient取代,大家可以从下面的url中查看相关的API,了解更详细的变动。
API:http://lucene.apache.org/solr/5_3_1/solr-solrj/index.html
HttpSolrClient server=new HttpSolrClient(url);
//设置对应请求的目标主机线程数为1000条
server.setDefaultMaxConnectionsPerHost(1000); server.setMaxTotalConnections(10000);
server.setConnectionTimeout(60000);//设置连接超时时间(单位毫秒) 1000
server.setSoTimeout(60000); 设置读数据超时时间(单位毫秒) 1000
server.setFollowRedirects(false);//遵循从定向
server.setAllowCompression(true);//允许压缩
若不使用Maven工程来操作Solr,须添加一下Jar依赖包
若使用Maven工程,需在pom.xml文件中添加下面依赖
<dependency>
<artifactId>solr-solrj</artifactId>
<groupId>org.apache.solr</groupId>
<version>1.4.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
定义一个solr server的java代码:
package com.teach.server;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
public class SolrServer {
private static SolrServer solrServer = null;
private static HttpSolrClient server=null;
private static String url="http://localhost:8085/solr/test";
public static synchronized SolrServer getInstance(){
if(solrServer==null){
solrServer=new SolrServer();
}
return solrServer;
}
public static HttpSolrClient getServer(){
if(server==null){
server = new HttpSolrClient(url);
server.setDefaultMaxConnectionsPerHost(1000);
server.setMaxTotalConnections(10000);
server.setConnectionTimeout(60000);//设置连接超时时间(单位毫秒) 1000
server.setSoTimeout(60000); 设置读数据超时时间(单位毫秒) 1000
server.setFollowRedirects(false);//遵循从定向
server.setAllowCompression(true);//允许压缩
}
return server;
}
}
SolrJ添加索引
HttpSolrClient server = SolrServer.getServer();
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "123456");
doc.addField("title_s", "test");
doc.addField("des_s", "test des");
try {
server.add(doc);
server.commit();
} catch (Exception e) {
e.printStackTrace();
}
Id:索引中的唯一ID,定义见配置。
title_s:动态字符串域定义,静态见配置。
SolrJ查询索引
HttpSolrClient server = SolrServer.getServer();
SolrQuery sQuery = new SolrQuery();