import org.compass.core.Compass;
import org.compass.core.CompassHits;
import org.compass.core.CompassQuery;
import org.compass.core.CompassSession;
import org.compass.core.CompassTemplate;
import org.compass.core.CompassQuery.SortDirection;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
...
public List<Product> searchProducts(String topMenuId, String middleMenuId, String menuId, String brandId,
String searchWord, String orderByColumn) {
Analyzer analyzer = new net.paoding.analysis.analyzer.PaodingAnalyzer();
Reader r = new StringReader(searchWord);
TokenStream ts = (TokenStream) analyzer.tokenStream("", r);
log.debug("=====paoding_analyzer start ====");
Token t;
try {
while ((t = ts.next()) != null) {
log.debug(t.termText());
}
} catch (IOException e) {
e.printStackTrace();
}
log.debug("=====paoding_analyzer end====");
Compass compass = compassTemplate.getCompass();
CompassSession session = compass.openSession();
List<Product> list = new ArrayList<Product>();
StringBuilder sql = new StringBuilder();
sql.append(searchWord);
boolean hasAnd = false;
if (StringUtils.isNotEmpty(menuId)) {
sql.append(hasAnd ? "" : " AND ");
sql.append(" product_menu_id:").append(menuId);
hasAnd = true;
}
if (StringUtils.isNotEmpty(brandId)) {
sql.append(hasAnd ? "" : " AND ");
sql.append(" product_brand_id:").append(brandId);
}
log.debug(sql.toString());
CompassQuery compassQuery = session.queryBuilder().queryString(sql.toString()).toQuery();
//排序部分,SortDirection.AUTO,SortDirection.REVERSE 逆序排序
if (StringUtils.isNotEmpty(orderByColumn)) {
if("click_ratio".equals(orderByColumn)){
compassQuery.addSort( orderByColumn ,
CompassQuery.SortPropertyType.INT,
SortDirection.AUTO);
}else if("saled_amount".equals(orderByColumn)){
compassQuery.addSort( orderByColumn ,
CompassQuery.SortPropertyType.INT,
SortDirection.AUTO);
}else if("web_price".equals(orderByColumn)){
compassQuery.addSort( orderByColumn ,
CompassQuery.SortPropertyType.FLOAT,
SortDirection.AUTO);
}else if("crtdate".equals(orderByColumn)){
compassQuery.addSort( orderByColumn ,
CompassQuery.SortPropertyType.STRING,
SortDirection.AUTO);
}
}
CompassHits hits = compassQuery.hits();
log.debug("hits:" + hits.getLength());
for (int i = 0; i < hits.length(); i++) {
Product p = (Product) hits.data(i);
// p.setName(hits.highlighter(i).fragment("name"));
// p.setBrand(hits.highlighter(i).fragment("brand"));
list.add(p);
}
return list;
}
...
Spring Compass (Lucene) 全文本搜索排序问题
最新推荐文章于 2024-11-14 20:02:43 发布