`
java_mike
  • 浏览: 83792 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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;
	}

//...


0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics