您的位置:首页 > 编程语言 > Java开发

五、在myeclipse中查询与添加索引实例

2015-12-20 21:36 411 查看
1.导入相关jar包



注意:jar的版本要根据solr的版本正确导入。

2.插入索引

public class SolrjPopulator {
public static void main(String[] args) throws IOException, SolrServerException {

HttpSolrServer server = new HttpSolrServer("http://localhost:8083/solr");

//======进行用户验证,因为tomcat中设定了用户验证,所以为了能连接服务器必需要验证用户,否则不能连通服务器
DefaultHttpClient m_client =(DefaultHttpClient)server.getHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin","admin");
m_client.addRequestInterceptor(new PreemptiveAuthInterceptor(),0);
(((DefaultHttpClient)m_client).getCredentialsProvider()).setCredentials(new AuthScope("localhost",8083), credentials);
//============
for (int i = 0; i < 3; i++) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("age", "27");
doc.addField("id", "5"+i);
doc.addField("name", "小刚子"+i);
server.add(doc);
//			if (i == 2)
server.commit(); // periodically flush
}
server.commit();
}
}


3.查询索引

public class SolrJSearcher {
public static void main(String[] args) throws MalformedURLException, SolrServerException {
HttpSolrServer solr = new HttpSolrServer("http://localhost:8083/solr/core0");

//====进行用户验证,因为tomcat中设定了用户验证,所以为了能连接服务器必需要验证用户,否则不能连通服务器
DefaultHttpClient m_client =(DefaultHttpClient)solr.getHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin","admin");
m_client.addRequestInterceptor(new PreemptiveAuthInterceptor(),0);
(((DefaultHttpClient)m_client).getCredentialsProvider()).setCredentials(new AuthScope("localhost",8083), credentials);
//======
ModifiableSolrParams params = new ModifiableSolrParams();
//params.set("q", "name:李*人");
params.set("q", "id:中国&name:中国");
params.set("defType", "dismax");
params.set("hl", "true");
params.set("hl.fl", "name");
//        params.set("start", "0");

QueryResponse response = solr.query(params);
SolrDocumentList results = response.getResults();
for (int i = 0; i < results.size(); ++i) {
System.out.println(results.get(i));
}
}
}

4.用户验证类

public class PreemptiveAuthInterceptor implements HttpRequestInterceptor {

public void process(HttpRequest request,
org.apache.http.protocol.HttpContext context) throws HttpException,
IOException {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);

// If no auth scheme avaialble yet, try to initialize it
// preemptively
if (authState.getAuthScheme() == null) {
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
Credentials creds = credsProvider.getCredentials(new AuthScope(
targetHost.getHostName(), targetHost.getPort()));
if (creds == null)
throw new HttpException(
"No credentials for preemptive authentication");
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息