Compass对搜索关键字实现高亮显示

例如搜"广东",实现后输出结果如下:<font color="red"><b>广</b></font><font color="red"><b>东</b></font>科学中心新老主任顺利交接.

实现步骤:

1、applicationContext-compass.xml中添加高亮配置

//...
<bean id="compass" class="org.compass.spring.LocalCompassBean">
<property name="resourceDirectoryLocations">
<list>
<value>classpath:cn/changtusoft</value>
</list>
</property>
<property name="connection">
<value>/lucene/indexes</value>
</property>


<property name="classMappings">
<list>
<value>cn.changtusoft.publicplatform.entity.synthesis.Trends</value>
</list>
</property>
<property name="compassConfiguration"
ref="annotationConfiguration" />

<property name="compassSettings">
<props>
<prop key="compass.transaction.factory">
org.compass.spring.transaction.SpringSyncTransactionFactory
</prop>
<prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">net.paoding.analysis.analyzer.PaodingAnalyzer </prop>

<!--高亮显示配置start-->
<prop key="compass.engine.highlighter.default.formatter.simple.pre">
<![CDATA[<font color="red"><b>]]>
</prop>
<prop key="compass.engine.highlighter.default.formatter.simple.post">
<![CDATA[</b></font>]]>
</prop>
<!--高亮显示配置end-->

</props>
</property>

<property name="transactionManager" ref="transactionManager" />
</bean>
//...


2、查询关键代码如下:

//...

@Override
public PagerModel searchByQueryString(String trends_title) {
List trendsList = new ArrayList();

Compass compass = compassTemplate.getCompass();
CompassSession session = compass.openSession();

// 从第几条记录开始
int offset = SystemContext.getOffset();
// 每页显示几条数据
int pageSize = SystemContext.getPagesize();

CompassTransaction tx = session.beginLocalTransaction();

CompassQuery compassQuery = session.queryBuilder().queryString("trends_title:"+trends_title).toQuery();
CompassHits hits = compassQuery.hits();

// 分页储存数据
for (int i = offset; i < offset + pageSize && i < hits.length(); i++) {
Trends p = (Trends)hits.data(i);
String trends_title_highlighter = hits.highlighter(i).fragment("trends_title");
p.setTrends_title(trends_title_highlighter);
trendsList.add(p);
}

tx.commit();

PagerModel pm = new PagerModel();
pm.setDatas(trendsList);
pm.setTotal(hits.length());

return pm;
}

//...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值