0

I want to give user the option to do case case sensitive or case insensitive search.

My idea is use a case sensitive analyzer to index the data and then use sensitive or insensitive analyzer to search depending on user input.

So I created my case sensitive analyzer and here is a simple of my code:

public final class CaseSensitiveStandardAnalyzer extends StopwordAnalyzerBase {
  @Override
  protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) {
    final StandardTokenizer src = new StandardTokenizer(matchVersion, reader);
    src.setMaxTokenLength(maxTokenLength);
    TokenStream tok = new StandardFilter(matchVersion, src);
    tok = new StopFilter(matchVersion, tok, stopwords);
    return new TokenStreamComponents(src, tok) {
      @Override
      protected void setReader(final Reader reader) throws IOException {
        src.setMaxTokenLength(CaseSensitiveStandardAnalyzer.this.maxTokenLength);
        super.setReader(reader);
      }
    };
  }

For indexing I used this:

Analyzer analyzer = new CaseSensitiveStandardAnalyzer(Version.LUCENE_46);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_46,analyzer);
IndexWriter indexWriter = new IndexWriter(indexDir,config);
indexWriter.addDocument(document);

For searching I used:

Analyzer analyzer;
if(caseSentive)
    analyzer = new CaseSensitiveStandardAnalyzer(Version.LUCENE_46);
else 
    analyzer = new StandardAnalyzer(Version.LUCENE_46);
QueryParser queryParser = new QueryParser(Version.LUCENE_46,"content", analyzer);
Query query = queryParser.parse(searchString);
//Search 
TopDocs results  = indexSearcher.search(query,10000);
ScoreDoc[] hits = results.scoreDocs;

When I tired this, the sensitive case worked, but the insensitive case didn't.

After more researching, I found that using a case-sensitive analyzer with a lower-care query will not work. Case-sensitive analyzer indexed work with case-sensitive query and case-insensitive analyzer indexed work with case-insensitive query, can anyone confirm this?

It seems to me the only reliable way to search both case-sensitive and case-insensitive is to index twice, one for each case, is this correct?

1 Answer 1

0

It seems to me the only reliable way to search both case-sensitive and case-insensitive is to index twice, one for each case, is this correct?

That would be a possible solution, but there are more optimal solutions for that use case: https://stackoverflow.com/a/2490441/867816

This might help, too: http://www.hascode.com/2014/07/lucene-by-example-specifying-analyzers-on-a-per-field-basis-and-writing-a-custom-analyzertokenizer/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.