简体   繁体   中英

How to do search of part of a word using lucene?

Its Ershad here.I am working on lucene. Now i am able to search the word.But if i type part of word, i am unable to get the results. Can you pls suggest what to be done.

For indexing, i am using the below code

writer = new IndexWriter(directory, new StandardAnalyzer(), true);
writer.SetUseCompoundFile(true);

doc.Add(Field.UnStored("text", parseHtml(html)));
doc.Add(Field.Keyword("path", relativePath));
writer.AddDocument(doc);

For searching, i am using the below code.

Query query = QueryParser.Parse(this.Query,"text",new StandardAnalyzer());

// create the result DataTable
this.Results.Columns.Add("title", typeof(string));
this.Results.Columns.Add("sample", typeof(string));
this.Results.Columns.Add("path", typeof(string));

// search
Hits hits = searcher.Search(query);

this.total = hits.Length();

If you refer to the Lucene Query Parser Syntax documentation , you will find that you can append an asterisk ( * ) to the end of your query to match all those words that begin with a particular string. For example, suppose you want to get results mentioning both "caterpillar" and "catamaran". Your search query would be "cat*".

However, if you are not in direct control of the search query (for example, if the user is entering their own search queries), then you may need a little trickery on the part of the QueryParser . My experience is solely with the Java version of Lucene. Hopefully the principles are the same with Lucene.NET.

In Java, you could extend the QueryParser class and override its newTermQuery(Term) method. Traditionally, this method would return a TermQuery object. However, the child class would instead return a PrefixQuery . For example:

public class PrefixedTermsQueryParser extends QueryParser {

    // Some constructors...

    protected Query newTermQuery(Term term) {
        return new PrefixQuery(term);
    }

}

I am not terribly sure what methods you could override in Lucene.NET, but I am sure there must be something similar. Looking at its documentation , it appears the QueryParser class has a method called GetFieldQuery . Perhaps this is the method you would have to override.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM