How to query lucene with "like" operator?

Freewind picture Freewind · Jul 22, 2010 · Viewed 26.4k times · Source

The wildcard * can only be used at the end of a word, like user*.

I want to query with a like %user%, how to do that?

Answer

Jon picture Jon · Jul 22, 2010

The trouble with LIKE queries is that they are expensive in terms of time taken to execute. You can set up QueryParser to allow leading wildcards with the following:

QueryParser.setAllowLeadingWildcard(true)

And this will allow you to do searches like:

*user*

But this will take a long time to execute. Sometimes when people say they want a LIKE query, what they actually want is a fuzzy query. This would allow you to do the following search:

user~

Which would match the terms users and fuser. You can specify an edit distance between the term in your query and the terms you want matched using a float value between 0 and 1. For example user~0.8 would match more terms than user~0.5.

I suggest you also take a look at regex query, which supports regular expression syntax for Lucene searches. It may be closer to what you really need. Perhaps something like:

.*user.*