Custom Analysis
The Tokenizers and Analyzers
that come with Ferret cater to most needs most of the time.
However, there may come a time when Ferret’s standard Analysis classes fall short and you need to
implement your own. In the following example, we’ll show you how to build
an Analyzer that automatically pads numbers to a
fixed width so that they will be correctly sorted for use
with a RangeQuery or
RangeFilter:
moduleFerret::AnalysisclassIntegerTokenizerdefinitialize(num,width)@num=num.to_i@width=widthenddefnexttoken=Token.new("%0#{@width}d"%@num,0,@width)if@num@num=nilreturntokenenddeftext=(text)@num=text.to_iendendclassIntegerAnalyzerdefinitialize(width)@width=widthenddeftoken_stream(field,input)returnIntegerTokenizer.new(input,@width)endendendincludeFerret::Analysisanalyzer=PerFieldAnalyzer.new(StandardAnalyzer.new)analyzer[:padded]=IntegerAnalyzer.new(5)index=Ferret::I.new(:analyzer=>analyzer)[5,50,500,5000,50000].eachdo|number|index<<{:padded=>number,:unpadded=>number}endputs"padded:"+index.search('padded:[10 10000]').to_sputs"unpadded:"+index.search('unpadded:[10 10000]').to_s
If you run this example, you’ll see that the
RangeQuery worked on the :padded_num field, even though you didn’t
explicitly pad the numbers as you added them to the field or the numbers
in the RangeQuery itself. The :num field query, on the other hand, failed
miserably.
In this chapter, we have covered analysis: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access