常用的几种查询方式

  • TermQuery词元使用
  • FuzzyQuery模糊查询使用
  • prefixQuery 通过前缀查询
  • wildcardQuery 通配符查询
  • BooleanQuery组合查询
  • 通过分词器进行查询parser
  • 通过分词器进行多字段查询

TermQuery词元使用

    public void termQueryTest() throws IOException {
    IndexSearcher indexSearcher = getIndexSearcher();
    
    //一个词元
    Term t = new Term("title", "lucene");
    TermQuery termQuery = new TermQuery(t);
    TopDocs topDocs =indexSearcher.search(termQuery, 3);
    
    printResult(indexSearcher, topDocs);
        
    }

FuzzyQuery模糊查询使用

    public void fuzzyQueryTest() throws IOException {
    IndexSearcher indexSearcher = getIndexSearcher();
    
    //模糊查询
    //通过两次置换,能够得到一个词条
    Term term = new Term("title","lucene");
    FuzzyQuery query = new FuzzyQuery(term);
    TopDocs topDocs =indexSearcher.search(query, 3);
        
    printResult(indexSearcher, topDocs);
        
    }

prefixQuery 通过前缀查询

    public void preQuery() throws IOException {
    IndexSearcher indexSearcher = getIndexSearcher();
        
    PrefixQuery query = new PrefixQuery(new Term("title","luce"));
    TopDocs topDocs =indexSearcher.search(query, 3);

    printResult(indexSearcher, topDocs);
        
    }

wildcardQuery 通配符查询

    public void wildcardQuery() throws IOException {
    IndexSearcher indexSearcher = getIndexSearcher();
    
    WildcardQuery query = new WildcardQuery(new Term("title","l*"));
    TopDocs topDocs =indexSearcher.search(query, 2);
    printResult(indexSearcher, topDocs);
    }

BooleanQuery组合查询

    public void booleanQuery() throws IOException {
    IndexSearcher indexSearcher = getIndexSearcher();
    BooleanQuery booleanQuery = new BooleanQuery();
    
        WildcardQuery wildcardQuery = new WildcardQuery(new Term("title", "l*"));
        booleanQuery.add(wildcardQuery, BooleanClause.Occur.MUST);
        
        PrefixQuery prefixQuery = new PrefixQuery(new Term("title", "m"));
    booleanQuery.add(prefixQuery, BooleanClause.Occur.MUST);

    TopDocs topDocs = indexSearcher.search(booleanQuery, Integer.MAX_VALUE);

    printResult(indexSearcher, topDocs);
    }

通过分词器进行查询parser

    public void parserQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();

    Analyzer analyzer = new IKAnalyzer();
    QueryParser queryParser = new QueryParser("content", analyzer);
    Query query =queryParser.parse("学习lucene");
        
    TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);

    printResult(indexSearcher, topDocs);
    }

通过分词器进行多字段查询

    public void multQuery() throws Exception {
    IndexSearcher indexSearcher = getIndexSearcher();

    MultiFieldQueryParser multiFieldQueryParser 
    = new MultiFieldQueryParser(new String[]{"title","content"},new IKAnalyzer());
    Query query =multiFieldQueryParser.parse("学习mac");
        
    TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);

    printResult(indexSearcher, topDocs);
}

标签: lucene

相关文章推荐

添加新评论,含*的栏目为必填