Elasticsearch 호출 Lucene 쿼리 인터페이스 원본 분석 6: 접두사 쿼리(Prefix)

11293 단어 elasticsearchLucene

Elasticsearch 호출 Lucene 쿼리 인터페이스 원본 분석 6: 접두사 쿼리(Prefix)

  • 소개
  • 조회 문법
  • 원본 분석

  • 소개


    접두사 조회는 설정에 있어서 단어 조회와 유사하다.접두사 검색은 이러한 문서와 일치할 수 있습니다. 이 문서의 특정 필드는 주어진 접두사로 시작됩니다.

    질의 문법


    예: 모든 제목 필드가cri로 시작하는 문서를 찾습니다: {"query": {"prefix": {"title": {value":"cri","boost": 3.0}}}}

    원본 분석

    '''(1)Elasticsearch code'''
    public class PrefixQueryParser implements QueryParser {
        public static final String NAME = "prefix";
        @Override
        public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
            XContentParser parser = parseContext.parser();
    
            XContentParser.Token token = parser.nextToken();
            if (token != XContentParser.Token.FIELD_NAME) {
                throw new QueryParsingException(parseContext.index(), "[prefix] query malformed, no field");
            }
            String fieldName = parser.currentName();
            String rewriteMethod = null;
    
            Object value = null;
            float boost = 1.0f;
            token = parser.nextToken();
            if (token == XContentParser.Token.START_OBJECT) {
                String currentFieldName = null;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else if (token.isValue()) {
                        if ("prefix".equals(currentFieldName)) {
                            value = parser.objectBytes();
                        } else if ("value".equals(currentFieldName)) {
                            value = parser.text();
                        } else if ("boost".equals(currentFieldName)) {
                            boost = parser.floatValue();
                        } else if ("rewrite".equals(currentFieldName)) {
                            rewriteMethod = parser.textOrNull();
                        }
                    } else {
                        throw new QueryParsingException(parseContext.index(), "[prefix] query does not support [" + currentFieldName + "]");
                    }
                }
                parser.nextToken();
            } else {
                value = parser.text();
                parser.nextToken();
            }
    
            if (value == null) {
                throw new QueryParsingException(parseContext.index(), "No value specified for prefix query");
            }
    
            MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(rewriteMethod, null);
    
            Query query = null;
            MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
            if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) {
                if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) {
                    String[] previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()});
                    try {
                        query = smartNameFieldMappers.mapper().prefixQuery(value, method, parseContext);
                    } finally {
                        QueryParseContext.setTypes(previousTypes);
                    }
                } else {
                    query = smartNameFieldMappers.mapper().prefixQuery(value, method, parseContext);
                }
            }
            if (query == null) {
                ''' Lucene PrefixQuery (Term("title","cri"))'''
                PrefixQuery prefixQuery = new PrefixQuery(new Term(fieldName, BytesRefs.toBytesRef(value)));
                ''' , cri cri , '''
                if (method != null) {
                    prefixQuery.setRewriteMethod(method);
                }
                query = prefixQuery;
            }
            query.setBoost(boost);
            return wrapSmartNameQuery(query, smartNameFieldMappers, parseContext);
        }
    }
    
    '''(2)Lucene code'''
    public class PrefixQuery extends AutomatonQuery {
       ....
    }
    public class AutomatonQuery extends MultiTermQuery {
       ....
    }
    public abstract class MultiTermQuery extends Query {
       ....
       @Override
       '''PrefixQuery MultiTermQuery , rewrite '''
       public final Query rewrite(IndexReader reader) throws IOException {
        return rewriteMethod.rewrite(reader, this);
      }
    }
    
    '''(3)Lucene  '''
    public void testPrefixQuery() throws Exception {
        Directory directory = newDirectory();
    
        String[] categories = new String[] {"/Computers",
                                            "/Computers/Mac",
                                            "/Computers/Windows"};
        RandomIndexWriter writer = new RandomIndexWriter(random(), directory);
        for (int i = 0; i < categories.length; i++) {
          Document doc = new Document();
          doc.add(newStringField("category", categories[i], Field.Store.YES));
          writer.addDocument(doc);
        }
        IndexReader reader = writer.getReader();
    
        ''' category "/Computers" '''
        PrefixQuery query = new PrefixQuery(new Term("category", "/Computers"));
        IndexSearcher searcher = newSearcher(reader);
        ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs;
        assertEquals("All documents in /Computers category and below", 3, hits.length);
    
        ''' category "/Computers/Mac" '''
        query = new PrefixQuery(new Term("category", "/Computers/Mac"));
        hits = searcher.search(query, 1000).scoreDocs;
        assertEquals("One in /Computers/Mac", 1, hits.length);
    
        ''' category '''
        query = new PrefixQuery(new Term("category", ""));
        hits = searcher.search(query, 1000).scoreDocs;
        assertEquals("everything", 3, hits.length);
        writer.close();
        reader.close();
        directory.close();
      }  

    좋은 웹페이지 즐겨찾기