Solr学习笔记五--solrj的使用(查询文档)

源代码:

package solrtest;

import java.net.MalformedURLException;
import java.rmi.server.ServerCloneException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

public class search {

	 public static SolrServer getSolrServer() throws MalformedURLException{  
	        //the instance can be reused  
	        return new CommonsHttpSolrServer("http://localhost:8983/solr/");  
	    }  
	public static void main(String[] args){
		// TODO Auto-generated method stub
		SolrServer solrServer = null;
		try {
			solrServer = getSolrServer();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SolrQuery query =new SolrQuery();
		query.setQuery("id:lskyne");
		QueryResponse rsp=null;
		try {
			rsp =solrServer.query(query);
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SolrDocumentList docs =rsp.getResults();
		for(SolrDocument solrDocument:docs)
		{
			String id =solrDocument.getFieldValue("id").toString();
			String title=solrDocument.getFieldValue("title").toString();
			System.out.println("id为"+id);
			System.out.println("title为"+title);
			Map<String, Object> map =solrDocument.getFieldValueMap();
			System.out.println(map.toString());
			Collection<String> result =solrDocument.getFieldNames();
			for(String r :result)
			{
				System.out.println(r+":"+solrDocument.getFieldValue(r));
			}
		}
	}

}


结果:


SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
id为lskyne
title为[welcome to solr]
{id=lskyne, title=[welcome to solr]}
id:lskyne
title:[welcome to solr]


你可能感兴趣的:(Solr学习笔记五--solrj的使用(查询文档))