package com.my.entity;
import java.util.Date;
import org.apache.solr.client.solrj.beans.Field;
public class Item {
@Field
private long id;
@Field
private String subject;
@Field
private String content;
@Field
private Date last_update_time;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.cOntent= content;
}
public Date getLast_update_time() {
return last_update_time;
}
public void setLast_update_time(Date last_update_time) {
this.last_update_time = last_update_time;
}
}
package com.my.solr;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrQuery.SortClause;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import com.my.entity.Item;
public class TestSolr {
public static void main(String[] args) throws IOException, SolrServerException {
String url = "http://localhost:8899/solr/mycore";
HttpSolrServer core = new HttpSolrServer(url);
core.setMaxRetries(1);
core.setConnectionTimeout(5000);
core.setParser(new XMLResponseParser()); // binary parser is used by default
core.setSoTimeout(1000); // socket read timeout
core.setDefaultMaxConnectionsPerHost(100);
core.setMaxTotalConnections(100);
core.setFollowRedirects(false); // defaults to false
core.setAllowCompression(true);
// ------------------------------------------------------
// remove all data
// ------------------------------------------------------
core.deleteByQuery("*:*");
// ------------------------------------------------------
// add item
// ------------------------------------------------------
Item item = new Item();
item.setId(1);
item.setSubject("solrj test");
item.setContent("this is my solrj test, ha ha.");
item.setLast_update_time(new Date());
core.addBean(item);
// ------------------------------------------------------
// add unicode item
// ------------------------------------------------------
Item item_cn = new Item();
item_cn.setId(2);
item_cn.setSubject("我的测试");
item_cn.setContent("这是一个神奇的网站!");
item.setLast_update_time(new Date());
core.addBean(item_cn);
// commit
core.commit();
// ------------------------------------------------------
// search
// ------------------------------------------------------
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
query.addSort(new SortClause("id", ORDER.desc));
QueryResponse response = core.query(query);
List- items = response.getBeans(Item.class);
for (Item i : items) {
System.out.println("id=" + i.getId() + "\tcOntent=" + i.getContent());
}
}
}