WEB开发网
开发学院软件开发Java 再谈compass----集成站内搜索 阅读

再谈compass----集成站内搜索

 2009-09-21 00:00:00 来源:WEB开发网   
核心提示: 4.建立索引Service 层代码 Java代码@Service@TransactionalpublicclassSearchServiceBeanextendsDaoSupportimplementsSearchService{@Resource(name="compass"

4.建立索引Service 层代码

Java代码   

@Service 
@Transactional 
public class SearchServiceBean extends DaoSupport implements SearchService { 
 @Resource(name = "compass") 
 Compass compass; 
 
/** 创建索引 **/ 
public void index(ProductInfo p) { 
 
CompassSession session = compass.openSession(); 
CompassTransaction tx = null; 
try { 
 tx = session.beginTransaction(); 
 session.create(p); 
 tx.commit(); 
} catch (Exception e) { 
 if (tx != null) { 
tx.commit(); 
 } 
 throw new RuntimeException(e); 
 } finally { 
 if (session != null) { 
 session.close(); 
 } 
 } 
 } 
 /** 删除一条索引 **/ 
 public void delete(ProductInfo p) { 
 CompassTemplate ct = new CompassTemplate(compass); 
 ct.delete(p); 
 } 
 /** 更新(重新创建)一条索引 **/ 
 public void update(final ProductInfo p) { 
 CompassTemplate ct = new CompassTemplate(compass); 
 
 CompassCallback<Object> action = new CompassCallback<Object>() { 
 
  public Object doInCompass(CompassSession session) 
   throws CompassException { 
  session.delete(p); 
  session.create(p); 
  return null; 
  } 
 
 }; 
 
 ct.execute(action); 
 } 
 /** 索引查询 **/ 
 public List<ProductInfo> find(final String keywords) { 
 CompassTemplate ct = new CompassTemplate(compass); 
 return ct.execute(new CompassCallback<List<ProductInfo>>() { 
 
  public List<ProductInfo> doInCompass(CompassSession session) 
   throws CompassException { 
  List<ProductInfo> result = new ArrayList<ProductInfo>(); 
  CompassQueryBuilder queryBuilder = session.queryBuilder(); 
  CompassHits hits = null; // session.find(query); 
  /** 在所有字段中查询 **/ 
  CompassQuery allPropertyQuery = queryBuilder.queryString(keywords).toQuery(); 
  hits = allPropertyQuery.hits(); 
  /** 在指定字段中查询 **/ 
  // CompassQuery query = queryBuilder.term("name", keywords); 
  // hits = query.hits(); 
  /** 指定范围查询 **/ 
//   CompassQuery dateRangeQuery = 
//   queryBuilder.between("postTime",startTime, endTime, true); 
//   hits = queryBuilder.bool() 
//   .addMust(allPropertyQuery) 
//   .addMust(dateRangeQuery) 
//   .toQuery() 
//   .hits(); 
//  System.out.println("---------"); 
  for (int i = 0; i < hits.length(); i++) { 
   ProductInfo p = (ProductInfo) hits.data(i); 
   /** 如果进行高亮的属性中没有出现关键字, 则返回null **/ 
//   String ht = hits.highlighter(i).fragment("name"); 
//   if (ht != null) { 
//   p.setName(ht); 
//   } 
//   String hc = hits.highlighter(i).fragment("code"); 
//   if (hc != null) { 
//   p.setCode(hc); 
//   } 
   result.add(p); 
  } 
  return result; 
  } 
 }); 
 } 

上一页  1 2 3 4 5 6 7  下一页

Tags:compass 集成 搜索

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接