solr基本操作代码示例
jopen
11年前
1、基本操作类
import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import com.xzhe.goods.bo.Goods; import com.xzhe.goods.dao.impl.GoodsDAO; public class SolrSearch { private static String tomcat_solr = "http://localhost:8983/solr"; private static CommonsHttpSolrServer solr = null; private static GoodsDAO goodsDAO = GoodsDAO.getInstance(); private static List<Goods> goodList = new ArrayList<Goods>(); // 初始化solr服务 public static void initiate() { try { solr = new CommonsHttpSolrServer(tomcat_solr); solr.setConnectionTimeout(100); solr.setDefaultMaxConnectionsPerHost(100); solr.setMaxTotalConnections(100); } catch (Exception e) { System.out.println("请检查tomcat服务器或端口是否开启!"); e.printStackTrace(); } } // 检测good是否有字段为空 public static Boolean CheckGood(Goods good) { if (null == good.getTitle() || good.getTitle().length() == 0) { return false; } else if (null == good.getGoodsId()) { return false; } else if (null == good.getStartTime()) { return false; } else if (null == good.getDiscount()) { return false; } else if (null == good.getCurPrice()) { return false; } else if (null == good.getSiteId()) { return false; } else if (null == good.getBuyNum()) { return false; } else { return true; } } // 将数据库中的时间转换为solr可接受的格式 public static String Convertime(String time) { time = time.replace(" ", "T"); time = time + "00Z"; return time; } // 添加list到索引,flag为false,在原有基础上添加,为false,重新添加、原有索引不会被删除 public static void addGoods(List<Goods> list, Boolean flag) { if (flag) { try { solr.deleteByQuery("*:*"); } catch (Exception e) { e.printStackTrace(); } } Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); for (int i = 0; i < list.size(); i++) { Goods good = list.get(i); if (CheckGood(good)) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("goodid", good.getGoodsId()); doc.addField("title", good.getTitle()); doc.addField("siteid", good.getSiteId()); doc.addField("buynum", good.getBuyNum()); doc.addField("starttime", Convertime(good.getStartTime() .toString())); doc.addField("discount", good.getDiscount()); doc.addField("curprice", good.getCurPrice()); docs.add(doc); } } try { solr.add(docs); solr.optimize(); solr.commit(); } catch (Exception e) { e.printStackTrace(); } } // 转换good到beans public static GoodsBeans ConvertGoodstoBeans(Goods good) { if (!CheckGood(good)) { return null; } GoodsBeans beans = new GoodsBeans(good.getGoodsId().toString(), good.getTitle(), good.getSiteId().toString(), good.getBuyNum(), good.getStartTime(), good.getDiscount(), good.getCurPrice()); return beans; } // 添加beans到索引 public static void addGoodsBeans(List<GoodsBeans> beansList) { try { solr.addBeans(beansList); } catch (Exception e) { e.printStackTrace(); } finally { try { solr.optimize(); solr.commit(); } catch (Exception e) { e.printStackTrace(); } } } // 删除所有索引 public static void DeleteAllIndex() { try { solr.deleteByQuery("*:*"); solr.commit(); } catch (Exception e) { e.printStackTrace(); } } // 根据ID删除索引 public static void DeleteIndex(List<String> ids) { try { solr.deleteById(ids); solr.commit(); } catch (Exception e) { e.printStackTrace(); } } // 进行搜索,field、key为查询(值或范围均可),start为起始查询位置,row为返回结果个数,sortfield为排序字段,flag中true升序、false降序,hightlight选择是否高亮返回,高亮字段为title public static QueryResponse Search(String[] field, String[] key, int start, int count, String[] sortfield, Boolean[] flag, Boolean hightlight) { if (null == field || null == key || field.length != key.length) { return null; } if (null == sortfield || null == flag || sortfield.length != flag.length) { return null; } SolrQuery query = null; try { if (field[0].equals("title")) { // query = new SolrQuery("*" + key + "*"); query = new SolrQuery(field[0] + ":" + key[0]); } else { query = new SolrQuery(field[0] + ":" + key[0]); } for (int i = 0; i < field.length; i++) { if (field[i].equals("title")) { // query = new SolrQuery("*" + key + "*"); query.addFilterQuery(field[i] + ":" + key[i]); } else { query.addFilterQuery(field[i] + ":" + key[i]); } } query.setStart(start); query.setRows(count); for (int i = 0; i < sortfield.length; i++) { if (flag[i]) { query.addSortField(sortfield[i], SolrQuery.ORDER.asc); } else { query.addSortField(sortfield[i], SolrQuery.ORDER.desc); } } if (null != hightlight) { query.setHighlight(true); // 开启高亮组件 query.addHighlightField("title");// 高亮字段 query.setHighlightSimplePre("<font color=\"red\">");// 标记 query.setHighlightSimplePost("</font>"); query.setHighlightSnippets(1); query.setHighlightFragsize(1000); } } catch (Exception e) { e.printStackTrace(); } System.out.println(query.toString()); QueryResponse rsp = null; try { rsp = solr.query(query); } catch (Exception e) { e.printStackTrace(); return null; } return rsp; } // 自动补全 public static String[] autoComplete(String prefix, int min) { String words[] = null; StringBuffer sb = new StringBuffer(""); SolrQuery query = new SolrQuery("*.*"); QueryResponse rsp = new QueryResponse(); try { query.setFacet(true); query.setQuery("*:*"); query.setFacetPrefix(prefix); query.addFacetField("title"); rsp = solr.query(query); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } if (null != rsp) { FacetField ff = rsp.getFacetField("title"); List<Count> countList = ff.getValues(); if (null == countList) { return null; } for (int i = 0; i < countList.size(); i++) { String tmp[] = countList.get(i).toString().split(" "); if (tmp[0].length() < 2) { continue; } sb.append(tmp[0] + " "); min--; if (min == 0) { break; } } words = sb.toString().split(" "); } else { return null; } return words; } public static void main(String[] args) { initiate(); // 建立索引 // goodList = goodsDAO.findAll(); // System.out.println("所有商品载入完成!"); // DeleteAllIndex(); // System.out.println("原有索引已清除!"); // System.out.println("添加索引开始!"); // long starttime = System.currentTimeMillis(); // addGoods(goodList, true); // long endtime = System.currentTimeMillis(); // System.out.println("共耗时" + (endtime - starttime) + "ms!"); // System.out.println("添加索引完成!"); // 进行查询 SolrDocumentList solrList = null; QueryResponse rsp = null; // rsp = Search("title", "*变形金* 蓝精灵", 0, 10, "buynum", false, true); // String field[] = { "title", "buynum", "discount", "starttime" }; // String key[] = { "变形金刚 哈利波特", "[90 TO 100]", "[2.0 TO 3.0]", // "[2011-07-18T00:00:00.000Z TO 2011-07-19T00:00:00.000Z]" }; String field[] = {"title"}; String key[] = {"牛奶"}; String sortfield[] = { "buynum" }; Boolean flag[] = { false }; long starttime = System.currentTimeMillis(); rsp = Search(field, key, 0, 10, sortfield, flag, true); long endtime = System.currentTimeMillis(); System.out.println("共耗时" + (endtime - starttime) + "ms!"); if (null != rsp) { solrList = rsp.getResults(); for (int i = 0; i < solrList.size(); i++) { System.out.println(solrList.get(i).toString()); } // 高亮显示部分 System.out.println("搜索结果共" + solrList.size() + "条!"); System.out.println(""); Map<String, Map<String, List<String>>> hightlight = rsp .getHighlighting(); List<GoodsBeans> tmpLists = rsp.getBeans(GoodsBeans.class); for (int i = 0; i < tmpLists.size(); i++) { String hlString = hightlight.get(tmpLists.get(i).getGoodId()) .get("title").toString(); if (null != hlString) { // System.out.println(hlString); } } } // 自动补全 // String words[] = autoComplete("哈利", 10); // if (null != words) { // System.out.println(words.length); // for (int i = 0; i < words.length; i++) { // System.out.println(words[i]); // } // } } }
2、bean
import java.util.Date; import org.apache.solr.client.solrj.beans.Field; public class GoodsBeans { @Field private String goodid; @Field private String title; @Field private String siteid; @Field private int buynum; @Field private Date starttime; @Field private double discount; @Field private double curprice; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSiteid() { return siteid; } public void setSiteid(String siteid) { this.siteid = siteid; } public int getBuynum() { return buynum; } public void setBuynum(int buynum) { this.buynum = buynum; } public Date getStarttime() { return starttime; } public void setStarttime(Date starttime) { this.starttime = starttime; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public double getCurprice() { return curprice; } public void setCurprice(double curprice) { this.curprice = curprice; } public void setGoodid(String goodid) { this.goodid = goodid; } public String getGoodId() { return goodid; } public GoodsBeans(){ } public GoodsBeans(String goodid, String title, String siteid, int buynum, Date starttime, double discount, double curprice) { this.goodid = goodid; this.title = title; this.siteid = siteid; this.buynum = buynum; this.starttime = starttime; this.discount = discount; this.curprice = curprice; } }