philomena/lib/philomena_query/parse/term_range_parser.ex

49 lines
1.6 KiB
Elixir
Raw Normal View History

defmodule PhilomenaQuery.Parse.TermRangeParser do
@moduledoc false
alias PhilomenaQuery.Parse.LiteralParser
alias PhilomenaQuery.Parse.NgramParser
2019-11-02 19:34:25 +01:00
# Unfortunately, we can't use NimbleParsec here. It requires
# the compiler, and we're not in a macro environment.
def parse(input, fields, {default_field, type}) do
2019-11-02 19:34:25 +01:00
tokens =
2019-11-02 21:31:55 +01:00
Enum.find_value(fields, fn {f, p} ->
2019-11-02 19:34:25 +01:00
field(input, f, p)
end)
tokens || [{parser(type), default_field}, range: :eq, value: input]
2019-11-02 19:34:25 +01:00
end
defp parser(:term), do: LiteralParser
defp parser(:ngram), do: NgramParser
2019-11-02 19:34:25 +01:00
defp field(input, field_name, field_parser) do
field_sz = byte_size(field_name)
case input do
<<^field_name::binary-size(field_sz), ":", value::binary>> ->
2019-11-02 22:02:46 +01:00
[{field_parser, field_name}, range: :eq, value: String.trim(value)]
2020-01-11 05:20:19 +01:00
2019-11-02 19:34:25 +01:00
<<^field_name::binary-size(field_sz), ".eq:", value::binary>> ->
2019-11-02 22:02:46 +01:00
[{field_parser, field_name}, range: :eq, value: String.trim(value)]
2020-01-11 05:20:19 +01:00
2019-11-02 19:34:25 +01:00
<<^field_name::binary-size(field_sz), ".gt:", value::binary>> ->
2019-11-02 22:02:46 +01:00
[{field_parser, field_name}, range: :gt, value: String.trim(value)]
2020-01-11 05:20:19 +01:00
2019-11-02 19:34:25 +01:00
<<^field_name::binary-size(field_sz), ".gte:", value::binary>> ->
2019-11-02 22:02:46 +01:00
[{field_parser, field_name}, range: :gte, value: String.trim(value)]
2020-01-11 05:20:19 +01:00
2019-11-02 19:34:25 +01:00
<<^field_name::binary-size(field_sz), ".lt:", value::binary>> ->
2019-11-02 22:02:46 +01:00
[{field_parser, field_name}, range: :lt, value: String.trim(value)]
2020-01-11 05:20:19 +01:00
2019-11-02 19:34:25 +01:00
<<^field_name::binary-size(field_sz), ".lte:", value::binary>> ->
2019-11-02 22:02:46 +01:00
[{field_parser, field_name}, range: :lte, value: String.trim(value)]
2020-01-11 05:20:19 +01:00
2019-11-02 19:34:25 +01:00
_ ->
nil
end
end
end