2007-09-24
Lucene进阶:and 和or的条件查询
关键字: Lucene and or 查询
在用Lucene实现全站搜索的过程中,很可能会遇到这样的问题,只所有某种特定的信息资源,而不是全部.如:某综合性站点,有新闻,产品,论坛,Blog,视频等资源,而搜索的时候先选一个类型(下拉列表),再输入关键字进行搜索(当然,这种情况可以直接用sql来实现,我们这里是基于lucene的实现考虑).这种情况下,就要用到and和or的查询了.这里假设索引已经建立好了(如何建立索引请参考:http://www.javaeye.com/topic/125599),索引字段为title(标题), type(资源类型,表示新闻还是产品,product为产品,news表新闻),则实现方法如下:
这里需要注意的就是BooleanClause.Occur[]数组,它表示多个条件之间的关系,BooleanClause.Occur.MUST表示and,BooleanClause.Occur.MUST_NOT表示not,BooleanClause.Occur.SHOULD表示or.
/**
* 根据信息分类和关键词进行查询
* @param type,资源的类型,其值为news或product
* @param searchKey,搜索的关键字
* @return Hits
*/
public Hits executeSearch(String type,String keyword)
{
Hits result = null;
if(type != null && !type.equals("") && keyword != null && !keyword.equals(""))
{
try
{
//根据关键字构造一个数组
String[] key = new String[]{keyword,type};
//同时声明一个与之对应的字段数组
String[] fields = {"title","type"};
//声明BooleanClause.Occur[]数组,它表示多个条件之间的关系
BooleanClause.Occur[] flags=new BooleanClause.Occur[]{BooleanClause.Occur.MUST,BooleanClause.Occur.MUST};
ChineseAnalyzer analyzer = new ChineseAnalyzer();
//用MultiFieldQueryParser得到query对象
Query query = MultiFieldQueryParser.parse(key, fields, flags, analyzer);
//c:/index表示我们的索引文件所在的目录
IndexSearcher searcher = new IndexSearcher("c:/index");
//查询结果
result = searcher.search(query);
} catch (Exception e)
{
e.printStackTrace();
}
}
return result;
}
这里需要注意的就是BooleanClause.Occur[]数组,它表示多个条件之间的关系,BooleanClause.Occur.MUST表示and,BooleanClause.Occur.MUST_NOT表示not,BooleanClause.Occur.SHOULD表示or.
评论
piaochunzhi
2007-09-24
BooleanClause.Occur[] flags=new BooleanClause.Occur[]{BooleanClause.Occur.MUST,BooleanClause.Occur.MUST};
2个 参数都是 BooleanClause.Occur.MUST 是什么 意思 是 && 这个意思 ????
2个 参数都是 BooleanClause.Occur.MUST 是什么 意思 是 && 这个意思 ????
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 28119 次
- 性别:

- 来自: 河北

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
深度技术GhostXP专业版V9 ...
还是V8.1版本成熟,速度很快,不错,可以一试!
-- by DavyLee -
2008年7月1日,盖茨离职 ...
不知道你的X年经验是几年,不过你确实缺少一些基础经验...
-- by e-ant -
2008年7月1日,盖茨离职 ...
引用这个是不是因为workspace中有eclipse的配置文件,删除那个.me ...
-- by DavyLee -
2008年7月1日,盖茨离职 ...
强阿我从来不用MyEclipse
-- by 王者之剑 -
2008年7月1日,盖茨离职 ...
引用第五:只要先用myEclipse建立了工作区,即使你把myEclipse卸掉 ...
-- by dogstar






评论排行榜