solrj的使用


1. 之前已经配置好了solr服务,并已经启动。


2.在工程中导入solr3.6.1中的jar

apache-solr-core-3.6.1.jar
apache-solr-solrj-3.6.1.jar


solrj-lib\commons-codec-1.6.jar
solrj-lib\commons-httpclient-3.1.jar
solrj-lib\commons-io-2.1.jar
solrj-lib\jcl-over-slf4j-1.6.1.jar
solrj-lib\slf4j-api-1.6.1.jar


junit-4.8.2.jar


直接上代码

public class Book implements Serializable{
	private Long id;
	private String name;
	private String author;
	private String title;
	private Date time;
	private String content;
	public Book() {
	}
	@Field("id")// 对应schema.xml中的  field name=id
	public void setId(Long id) {
		this.id = id;
	}
	@Field("name")
	public void setName(String name) {
		this.name = name;
	}
	@Field("author")
	public void setAuthor(String author) {
		this.author = author;
	}
	@Field("title")
	public void setTitle(String title) {
		this.title = title;
	}
	@Field("last_modified")
	public void setTime(Date time) {
		this.time = time;
	}
	@Field("content")// 这个是自己添加的中文分词 <field name="content" type="textComplex" indexed="true" stored="true"/> 
	public void setContent(String content) {
		this.content = content;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", author=" + author
				+ ", title=" + title + ", time=" + time + ", content="
				+ content + "]";
	}
	public Book(Long id, String name, String author, String title, Date time,
			String content) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.title = title;
		this.time = time;
		this.content = content;
	}
	...
//get
 }

来个测试类

public class SolrTest {
	private SolrServer server;
	@Before
	public void before(){
		try {
			server = new CommonsHttpSolrServer("http://localhost:8088/solr");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * <p>插入数据</p>
	 */
	@Test
	public void testIndex(){
		List<Book> list = new ArrayList<Book>(5);
		for (int i=1; i<=5;i++) {
			Book b = new Book(new Long(i), "书籍"+i, "作者"+i, "标题"+i, new Date(), "这"+i+"本书的类容不错");
			list.add(b);
		}
		try {
			UpdateResponse resp= server.addBeans(list);
			System.out.println(resp);
			server.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testSearch(){
		SolrQuery query = new SolrQuery("name:书籍");
 //title由于schema.xml中定义为multiValued="true" 多值(数组),而我的属性定义为String,直接获取会报错的
 query.setFields("id	","name","author","last_modified","content");//指定查询域
		try {
			QueryResponse resp = server.query(query);
			List<Book> books = resp.getBeans(Book.class);
			for (Book book : books) {
				System.out.println(book);
			}
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
	}
}



你可能感兴趣的:(solrj的使用)