-
Notifications
You must be signed in to change notification settings - Fork 3
/
term_parser.rb
39 lines (34 loc) · 939 Bytes
/
term_parser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'parslet'
module TermParser
# This is a simple parser that matches a sequence of non-whitespace characters
# and converts it to an Elasticsearch match query.
class QueryParser < Parslet::Parser
rule(:term) { match('[^\s]').repeat(1).as(:term) }
rule(:space) { match('\s').repeat(1) }
rule(:query) { (term >> space.maybe).repeat.as(:query) }
root(:query)
end
class QueryTransformer < Parslet::Transform
rule(:term => simple(:term)) { term.to_s }
rule(:query => sequence(:terms)) { Query.new(terms) }
end
# A query represented by a list of parsed user terms
class Query
attr_accessor :terms
def initialize(terms)
self.terms = terms
end
def to_elasticsearch
{
:query => {
:match => {
:title => {
:query => terms.join(" "),
:operator => "or"
}
}
}
}
end
end
end