当前位置:首页 » SEO知识

Solr之Solrj封装

2018-04-11 08:21 本站整理 浏览(7)

基本信息:

版本:7.0.0

单机版,cloud版本有所区分

步骤:

1.依赖:

<dependency>
	<groupId>org.apache.solr</groupId>
	<artifactId>solr-solrj</artifactId>
	<version>7.0.0</version>
</dependency>

2.业务封装代码:

public class SearchClient {
	private SolrClient client;

	public SearchClient(String baseSolrUrl, String core) {
		client = new HttpSolrClient.Builder(baseSolrUrl + core).build();
	}

	 
	public List<Article> search(String kw,  int rows)
			throws Exception {
		SolrQuery query = new SolrQuery();
		query.setQuery("title:" + kw);
		query.setQuery("type:" + kw);
		query.setQuery("content:" + kw);
		query.setRows(rows);
		QueryResponse queryResponse = client.query(query);
		SolrDocumentList results = queryResponse.getResults();
		List<Article> items =new ArrayList<Article>();
		  for (SolrDocument solrDocument : results) {
			  Article item=new Article();
			  item.setId(solrDocument.get("id")+"");
			  item.setTitle(solrDocument.get("title")+"");
			  item.setType(solrDocument.get("type")+"");
			  items.add(item);
		}
		
		return items;

	}

	public void delete(String id) throws Exception {
		client.deleteById(id);
		client.commit();
	}

	public void add(List<Article> items) throws Exception {
		for (Article item : items) {
			SolrInputDocument solrInputDocument = new SolrInputDocument();
			solrInputDocument.addField("id", item.getId());
			solrInputDocument.addField("content", item.getContent());
			solrInputDocument.addField("title", item.getTitle());
			solrInputDocument.addField("type", item.getType());
			client.add(solrInputDocument);
		}
		
		client.commit();
	}

	public void closeQuietly() {
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

测试:

public static void add() throws Exception {
	String baseSolrUrl="http://localhost:8983/solr/";
	String core="someabcd";
	SearchClient client=new SearchClient(baseSolrUrl,core);
	List<Article> items=new ArrayList<Article>();
	List<String> lines=FileUtils.readLines(new File("E:/data/test.data00"));
	for (String line : lines) {
		Article item=JSON.parseObject(line, Article.class);
		item.setId(CommonUtils.getUUID32());
		items.add(item);
	}
	client.add(items);
	client.closeQuietly();
}
public static void search() throws Exception {
	String baseSolrUrl="http://localhost:8983/solr/";
	String core="someabcd";
	
	SearchClient client=new SearchClient(baseSolrUrl,core);
	List<Article> items=client.search("Apache版本", 10);
	System.out.println(items);
	client.closeQuietly();
}
public static void del(String id) throws Exception {
	String baseSolrUrl="http://localhost:8983/solr/";
	String core="someabcd";
	
	SearchClient client=new SearchClient(baseSolrUrl,core);
	client.delete(id);
	client.closeQuietly();
}

 

ps:

如果想直接反序列为Bean那么需要用其自定义注解

@Field("id")

private String id;

@Field

private String title;