您的位置:首页 > 其它

Lucene进阶:and 和or的条件查询

2009-06-08 15:51 471 查看
在用Lucene实现全站搜索的过程中,很可能会遇到这样的问题,只所有某种特定的信息资源,而不是全部.如:某综合性站点,有新闻,产品,论
坛,Blog,视频等资源,而搜索的时候先选一个类型(下拉列表),再输入关键字进行搜索(当然,这种情况可以直接用sql来实现,我们这里是基于
lucene的实现考虑).这种情况下,就要用到and和or的查询了.这里假设索引已经建立好了(如何建立索引请参
考:http://www.javaeye.com/topic/125599),索引字段为title(标题),
type(资源类型,表示新闻还是产品,product为产品,news表新闻),则实现方法如下:

Java代码

/**

* 根据信息分类和关键词进行查询

* @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;

}

/**
* 根据信息分类和关键词进行查询
* @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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: