elasticsearch和lucene4查询语法比较

查询短语在单个字段上:
elasticsearch:

1
2
 QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder("汉语词法或其它汉语语言知识进行分词");
 queryBuilder.analyzer("ik").field("title");

lucene4:

1
2
3
 QueryParser qp = new QueryParser(Version.LUCENE_42, "title",  new IKAnalyzer(true));
 qp.setDefaultOperator(QueryParser.AND_OPERATOR);
 Query q = qp.parse("汉语词法或其它汉语语言知识进行分词");

查询短语在多个字段上查找:
elasticsearch:

1
2
 QueryStringQueryBuilder queryBuilder = new QueryStringQueryBuilder("汉语词法或其它汉语语言知识进行分词");
 queryBuilder.analyzer("ik").field("title").field("content");

lucene4:

1
2
3
4
5
6
7
 Analyzer analyzer=new IKAnalyzer(true);
 MultiFieldQueryParser.parse(Version.LUCENE_42, new String[]{"汉语词法或其它汉语语言知识进行分词"},new String[]{"title","content"},analyzer);
//默认在两个字段之间是或关系。如果需要改变两个字段之间的关系,请使用以下方法。
//查询字段必须在title字段,在content字段为或关系
BooleanClause.Occur[] flags = {BooleanClause.Occur.MUST,BooleanClause.Occur.SHOULD};
Analyzer analyzer=new IKAnalyzer(true);
MultiFieldQueryParser.parse(Version.LUCENE_42,"汉语词法或其它汉语语言知识进行分词",new String[]{"title","content"},flags,analyzer);

term query:
elasticsearch:

1
TermQueryBuilder t=new TermQueryBuilder("title", "中国");

lucene4:

1
2
 Term term = new Term("title", "中国");
TermQuery query=new TermQuery(term);

组合查询:
需求:查询在科技频道,体育频道下,文章类型为3,标题和内容包含”全面发展的中国”的文章
elasticsearch:

1
2
3
4
5
6
7
8
9
List<Long> channelids = new ArrayList<Long>();
channelids.add("4");
channelids.add("5");
FilteredQueryBuilder queryBuilder= QueryBuilders.filteredQuery(
                    new QueryStringQueryBuilder("全面发展的中         国").analyzer("ik").field("title").filed("content"), 
                    FilterBuilders.boolFilter()
                    .should(FilterBuilders.termsFilter("channelid", channelids))
                    .must(FilterBuilders.termFilter("model", 4))
                    );

lucene4:

1
2
3
4
5
6
7
8
9
10
11
12
13
Analyzer analyzer=new IKAnalyzer(true);
  Query query =MultiFieldQueryParser.parse(Version.LUCENE_42, new String[]{"全面发展的中国"},new String[]{"title","content"},analyzer);
Term term1 = new Term("channelid", "4");
Term term2 = new Term("channelid", "5");
Term term3 = new Term("model", "4");
 TermQuery q1 = new TermQuery(term1);  
 TermQuery q2 = new TermQuery(term2);  
 TermQuery q3 = new TermQuery(term3);  
 BooleanQuery booleanQuery = new BooleanQuery();  
 booleanQuery.add(q1, BooleanClause.Occur.SHOULD); 
booleanQuery.add(q2, BooleanClause.Occur.SHOULD); 
booleanQuery.add(q3, BooleanClause.Occur.MUST); 
booleanQuery.add(query, BooleanClause.Occur.MUST);

本文固定链接: http://www.chepoo.com/elasticsearch-lucene4-compare-query-syntax.html | IT技术精华网

你可能感兴趣的:(elasticsearch和lucene4查询语法比较)