I am a greenhand on Lucene, and I want to implement auto suggest, just like google, when I input a character like 'G', it would give me a list, you can try your self.
I have searched on the whole net. Nobody has done this , and it gives us some new tools in package suggest
But i need an example to tell me how to do that
Is there anyone can help ?
I'll give you a pretty complete example that shows you how to use
AnalyzingInfixSuggester
. In this example we'll pretend that we're Amazon, and we want to autocomplete a product search field. We'll take advantage of features of the Lucene suggestion system to implement the following:First I'll define a simple class to hold information about a product in Product.java:
To index records in with the
AnalyzingInfixSuggester
'sbuild
method you need to pass it an object that implements theorg.apache.lucene.search.suggest.InputIterator
interface. AnInputIterator
gives access to the key, contexts, payload and weight for each record.The key is the text you actually want to search on and autocomplete against. In our example, it will be the name of the product.
The contexts are a set of additional, arbitrary data that you can use to filter records against. In our example, the contexts are the set of ISO codes for the countries we will ship a particular product to.
The payload is additional arbitrary data you want to store in the index for the record. In this example, we will actually serialize each
Product
instance and store the resulting bytes as the payload. Then when we later do lookups, we can deserialize the payload and access information in the product instance like the image URL.The weight is used to order suggestion results; results with a higher weight are returned first. We'll use the number of sales for a given product as its weight.
Here's the contents of ProductIterator.java:
In our driver program, we will do the following things:
StandardTokenizer
.AnalyzingInfixSuggester
using the RAM directory and tokenizer.ProductIterator
.Here's the driver program, SuggestProducts.java:
And here is the output from the driver program:
Appendix
There's a way to avoid writing a full
InputIterator
that you might find easier. You can write a stubInputIterator
that returnsnull
from itsnext
,payload
andcontexts
methods. Pass an instance of it toAnalyzingInfixSuggester
'sbuild
method:Then for each item you want to index, call the
AnalyzingInfixSuggester
add
method:After you've indexed everything, call
refresh
:If you're indexing large amounts of data, it's possible to significantly speedup indexing using this method with multiple threads: Call
build
, then use multiple threads toadd
items, then finally callrefresh
.[Edited 2015-04-23 to demonstrate deserializing info from the
LookupResult
payload.]