Elasticsearch源码分析一--调用Lucene查询接口之match_all查询

  • 简介
  • 查询语法
  • 源码分析

简介

match_all查询是Elasticsearch中最简单的查询之一。它使我们能够匹配索引中的所有文件。
可以在查询中包含加权值,它将赋给所有跟它匹配的文档

查询语法

例1:得到索引中的所有文档,可以发送以下查询:
{
“query” : {
“match_all” : {}
}

例2:在match_all查询中给所有文档加上2.0的加权,可以发送以下查询:
{
“query” : {
“match_all” : {
“boost” : 2.0
} } }

源码分析

'''(1)Elasticsearch code'''
public class MatchAllQueryParser implements QueryParser {

    public static final String NAME = "match_all";

    @Override
    public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        float boost = 1.0f;
        String normsField = null;
        String currentFieldName = null;

        XContentParser.Token token;
        while (((token = parser.nextToken()) != XContentParser.Token.END_OBJECT && token != XContentParser.Token.END_ARRAY)) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token.isValue()) {
                '''解析加权值'''
                if ("boost".equals(currentFieldName)) {
                    boost = parser.floatValue();
                } else if ("norms_field".equals(currentFieldName) || "normsField".equals(currentFieldName)) {
                    normsField = parseContext.indexName(parser.text());
                } else {
                    throw new QueryParsingException(parseContext.index(), "[match_all] query does not support [" + currentFieldName + "]");
                }
            }
        }
        '''未设置加权值时,直接返回XConstantScoreQuery对象,We do not use MatchAllDocsQuery, its slower than the one below '''
        if (boost == 1.0f && normsField == null) {
            return Queries.MATCH_ALL_QUERY;
        }

        '''构造Lucene的MatchAllDocsQuery并返回'''
        MatchAllDocsQuery query = new MatchAllDocsQuery();
        query.setBoost(boost);
        return query;
    }
}
'''(2)Lucene code'''
public final class MatchAllDocsQuery extends Query {

  @Override
  '''创建Weight对象树'''
  public Weight createWeight(IndexSearcher searcher, boolean needsScores) {
    return new RandomAccessWeight(this) {
      @Override
      protected Bits getMatchingDocs(LeafReaderContext context) throws IOException {
      '''返回所有文档,Lucene中查询结果是以bit数组方式返回,每一个bit位对应一个DocID,bit值为1表示该DocID对应的文档matched'''
        return new Bits.MatchAllBits(context.reader().maxDoc());
      }
    };
  }


版权声明:本文为zhufenglonglove原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。