PhraseQuery against title field and QueryParser against a catch all field do not result in the results I expect

99封情书 提交于 2019-12-04 21:04:39

The way you build up your query for the title I suspect you never get hits originating from the title clause.

You build the PhraseQuery to look for a single term: "Chicken Parmesan", but when you indexed it, the StandardAnalyzer produced two Terms: "chicken" and "parmesan". You need to build the PhraseQuery with those two terms.

You can use the QueryParser for this purpose:

    QueryParser qp = new QueryParser("keyWord", new StandardAnalyzer());
    Query q = qp.Parse("+(keyWord:chicken KeyWord:parmesan) title:\"Chicken Parmesan\"~12^5.0");
    var hits = searcher.Search(q);

If you dont want to use the QueryParser, use the TokenStream api to break your text in tokens:

    PhraseQuery titleQuery = new PhraseQuery();
    titleQuery.SetSlop(12);
    titleQuery.SetBoost(5);
    BooleanQuery keywordQuery = new BooleanQuery();

    var standard = new StandardAnalyzer();
    TokenStream tokens = standard.TokenStream("title", new StringReader("Chicken Parmesan"));
    List<Term> terms = new List<Term>();
    while (tokens.IncrementToken())
    {
        TermAttribute termAttribute = (TermAttribute)tokens.GetAttribute(typeof(TermAttribute));

        titleQuery.Add(new Term("title", termAttribute.Term()));

        keywordQuery.Add(
            new TermQuery(
                new Term("keyWord", termAttribute.Term())),
            BooleanClause.Occur.SHOULD);  
    }

    BooleanQuery query = new BooleanQuery();
    query.Add(keywordQuery, BooleanClause.Occur.MUST);
    query.Add(titleQuery, BooleanClause.Occur.SHOULD);

    var hits = searcher.Search(query);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!