第六章. Java调用Solr

阅读更多

1. 引入相关Jar包


	org.apache.solr
	solr-solrj
	6.5.0



	com.alibaba
	fastjson
	1.2.12

2.调用Solr搜索数据

    * Solr测试类SolrTest.java

 

public class SolrTest {
	private static Logger log = LogManager.getLogger();

	public static void main(String[] args) throws Exception {
		String solrUrl = "http://localhost:10001/solr/core_test";
		HttpSolrClient client = new HttpSolrClient.Builder(solrUrl).build();
		SolrQuery query = new SolrQuery();
		query.set("wt", "json");
		// 查询字符串,查询名称中有James/Curry,并且年龄为20~30(包含)的记录
		query.set("q", "name:(James Curry) AND age:[20 TO 30]");
		// 返回的记录包含哪些字段,多个用逗号空格分割
		query.set("fl", "id,name,age");
		query.set("sort", "age ASC,name DESC");
		// 过滤查询:年龄范围25~30
		// query.set("fq", "age:[25 TO 30]");

		// ***********高亮 setting start***********
		// 开启高亮
		query.set("hl", "true");
		// 高亮字段
		query.set("hl.fl", "name");
		// 高亮格式(前)
		query.set("hl.simple.pre", "");
		// 高亮格式(后)
		query.set("hl.simple.post", "");
		// ***********高亮 setting end***********

		// 分页,返回数据由第几条记录开始
		query.setStart(0);
		// 分页,返回记录的条数
		query.setRows(10);
		//
		QueryResponse response = client.query(query);
		SolrDocumentList result = response.getResults();
		//
		List starList = response.getBeans(Star.class);
		log.info("total:{},start:{},end:{}",result.getNumFound(),result.getStart(),result.getStart()+result.size());
		log.info("----------列表数据----------");
		for (Star star : starList) {
			log.info(JSONObject.toJSONString(star));
		}
		log.info("----------高亮----------");
		Map>> hlMap = response.getHighlighting();
		Iterator>>> hlIterator = hlMap.entrySet().iterator();
		while(hlIterator.hasNext()){
			Entry>> hlItem = hlIterator.next();
			log.info("id->{},highlight->{}",hlItem.getKey(),hlItem.getValue());
		}
	}
}
  
    * Solr搜索记录对应实体类Star.java
import org.apache.solr.client.solrj.beans.Field;

public class Star {
	@Field("id")
	private String id;
	@Field("name")
	private String name;
	@Field("age")
	private int age;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}
 搜索结果:
2017-04-21 17:17:37.765 [main] INFO  - total:2,start:0,end:2
cn.tinyf.demo.solr.SolrTest
2017-04-21 17:17:37.766 [main] INFO  - ----------列表数据----------
cn.tinyf.demo.solr.SolrTest
2017-04-21 17:17:37.820 [main] INFO  - {"age":27,"id":"66654e81-c1a9-4961-b782-5513f0928f2a","name":"James Harden"}
cn.tinyf.demo.solr.SolrTest
2017-04-21 17:17:37.820 [main] INFO  - {"age":28,"id":"18f483cc-afda-4cc5-926e-5035bc427239","name":"Curry"}
cn.tinyf.demo.solr.SolrTest
2017-04-21 17:17:37.820 [main] INFO  - ----------高亮----------
cn.tinyf.demo.solr.SolrTest
2017-04-21 17:17:37.820 [main] INFO  - id->66654e81-c1a9-4961-b782-5513f0928f2a,highlight->{name=[James Harden]}
cn.tinyf.demo.solr.SolrTest
2017-04-21 17:17:37.821 [main] INFO  - id->18f483cc-afda-4cc5-926e-5035bc427239,highlight->{name=[Curry]}
cn.tinyf.demo.solr.SolrTest
 
3.添加&更新文档(记录)
更新主要方法有(反括号表示有带此参数的重载方法):
  • addBean(Object [,int])
  • add(SolrInputDocument [,int])
测试代码:
import org.apache.solr.client.solrj.impl.HttpSolrClient;

import cn.tinyf.demo.Utils;

public class SolrUpdateTest {
	private static Scanner reader;

	public static void main(String[] args) throws Exception {
		String solrUrl = "http://localhost:10001/solr/core_test";
		HttpSolrClient solrClient = null;
		try {
			// 构造输入
			reader = new Scanner(System.in);
			// 新建solr客户端
			solrClient = new HttpSolrClient.Builder(solrUrl).build();

			int menu = 0;
			String line = null;
			Star data;
			while ((menu = selectMenu()) != 0) {
				switch (menu) {
				// 增加文档
				case 1:
					System.out.println(">>>增加记录<<<");
					System.out.print("请输入name:");
					line = reader.nextLine();
					if (Utils.isEmpty(line)) {
						break;
					}
					data = new Star();
					data.setName(line);
					System.out.print("请输入age:");
					line = reader.nextLine();
					if (Utils.isEmpty(line) || !line.trim().matches("\\d*")) {
						break;
					}
					data.setAge(Integer.parseInt(line));
					data.setId(Utils.uuid());
					solrClient.addBean(data, 100);
					System.out.println(">>>To do add next,id->" + line);
					break;
				// 修改
				case 2:
					System.out.println(">>>修改记录<<<");
					System.out.print("请输入记录ID:");
					line = reader.nextLine();
					if (Utils.isNotEmpty(line)) {
						solrClient.deleteById(line);
					}
					data = new Star();
					data.setId(line);
					System.out.print("请输入name:");
					line = reader.nextLine();
					if (Utils.isEmpty(line)) {
						break;
					}
					data.setName(line);
					System.out.print("请输入age:");
					line = reader.nextLine();
					if (Utils.isEmpty(line) || !line.trim().matches("\\d*")) {
						break;
					}
					data.setAge(Integer.parseInt(line));
					solrClient.addBean(data, 100);
					System.out.println(">>>To do update next,id->" + line);
					break;
				// 刪除
				case 3:
					System.out.println(">>>删除记录<<<");
					System.out.print("请输入记录ID:");
					line = reader.nextLine();
					if (Utils.isNotEmpty(line)) {
						solrClient.deleteById(line);
					}
					System.out.println(">>>To do delete next,id->" + line);
					break;
				// 马上提交更改
				case 4:
					System.out.println(">>>Commit right now!");
					solrClient.commit();
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			reader.close();
			if (solrClient != null) {
				solrClient.commit();
			}
		}
	}

	private static int selectMenu() {
		do {
			System.out.println("******Solr Menu******");
			System.out.println("*1.增加记录");
			System.out.println("*2.更新记录");
			System.out.println("*3.删除记录");
			System.out.println("*4.提交更改");
			System.out.println("*0.退出");
			System.out.print("*********************\n请选择:");
			String line = reader.nextLine();
			if (line.matches("\\s*[0-4]\\s*")) {
				return Integer.parseInt(line);
			} else {
				System.out.println(">>>选择错误(" + line + "),请重新选择<<<");
			}
		} while (true);
	}
}
 
返回目录

你可能感兴趣的:(第六章. Java调用Solr)