当前位置:  开发笔记 > 编程语言 > 正文

在Lucene的多字段搜索

如何解决《在Lucene的多字段搜索》经验,为你挑选了1个好方法。

我需要使用Lucene在Books数据库上进行多字段级搜索.

例如:我的搜索条件是这样的:

(Author:a1 and title:t1)  OR (Author:a2 and title:t2) OR (Author:a3 and title:t3) 

其中a1,t1等等分别​​是作者姓名和书名.如何获取为此类条件构建的Lucene Query对象?

谢谢!



1> Kai Chan..:

以下代码假定a1,a2,a3,t1,t2,t3是术语.如果它们是短语,则需要使用PhraseQuery而不是TermQuery.

    // Create a BooleanQuery for (Author:a1 and title:t1)

BooleanQuery a1AndT1 = new BooleanQuery();
a1AndT1.add(new TermQuery(new Term("Author", "a1")), BooleanClause.Occur.MUST);
a1AndT1.add(new TermQuery(new Term("title", "t1")), BooleanClause.Occur.MUST);

// Create a BooleanQuery for (Author:a2 and title:t2)

BooleanQuery a2AndT2 = new BooleanQuery();
a2AndT2.add(new TermQuery(new Term("Author", "a2")), BooleanClause.Occur.MUST);
a2AndT2.add(new TermQuery(new Term("title", "t2")), BooleanClause.Occur.MUST);

// Create a BooleanQuery for (Author:a3 and title:t3)

BooleanQuery a3AndT3 = new BooleanQuery();
a3AndT3.add(new TermQuery(new Term("Author", "a3")), BooleanClause.Occur.MUST);
a3AndT3.add(new TermQuery(new Term("title", "t3")), BooleanClause.Occur.MUST);

// Create a BooleanQuery that combines the OR-clauses

BooleanQuery query = new BooleanQuery();
query.add(a1AndT1, BooleanClause.Occur.SHOULD);
query.add(a2AndT2, BooleanClause.Occur.SHOULD);
query.add(a3AndT3, BooleanClause.Occur.SHOULD);

// As you can see, the resulting Lucene query is 
// (+Author:a1 +title:t1) (+Author:a2 +title:t2) (+Author:a3 +title:t3)
// which behaves the same as something like
// (Author:a1 and title:t1) OR (Author:a2 and title:t2) OR (Author:a3 and title:t3)

System.out.println(query); 

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有