-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (90 loc) · 2.23 KB
/
main.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"bytes"
"encoding/json"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
"github.com/olivere/elastic"
)
var (
lex = lexer.MustSimple([]lexer.SimpleRule{
{Name: "Key", Pattern: `[a-zA-Z_]+`},
{Name: "Value", Pattern: `[a-zA-Z0-9_-]+`},
{Name: "Punct", Pattern: `[():]`},
{Name: "whitespace", Pattern: `\s+`},
})
parser = participle.MustBuild[RootQuery](participle.Lexer(lex))
)
type (
RootQuery = OrQuery
OrQuery struct {
Head AndQuery `@@`
Tail []OrTail `@@*`
}
OrTail struct {
Separator struct{} `'OR'`
Tail AndQuery `@@*`
}
AndQuery struct {
Head SimpleOrGroup `@@`
Tail []AndTail `@@*`
}
AndTail struct {
Separator struct{} `'AND'`
Tail SimpleOrGroup `@@*`
}
SimpleOrGroup struct {
SimpleQuery *SimpleQuery `@@`
GroupQuery *RootQuery `| '(' @@ ')'`
}
SimpleQuery struct {
Key string `@Key`
Separator struct{} `':'`
Value string `@Value`
}
)
func (o *OrQuery) ToElastic() elastic.Query {
queries := make([]elastic.Query, 0)
queries = append(queries, o.Head.ToElastic())
for _, tail := range o.Tail {
queries = append(queries, tail.Tail.ToElastic())
}
return elastic.NewBoolQuery().Should(queries...)
}
func (o *AndQuery) ToElastic() elastic.Query {
queries := make([]elastic.Query, 0)
queries = append(queries, o.Head.ToElastic())
for _, tail := range o.Tail {
queries = append(queries, tail.Tail.ToElastic())
}
return elastic.NewBoolQuery().Filter(queries...)
}
func (o *SimpleOrGroup) ToElastic() elastic.Query {
if o.SimpleQuery != nil {
return o.SimpleQuery.ToElastic()
}
if o.GroupQuery != nil {
return o.GroupQuery.ToElastic()
}
panic("invalid tree")
}
func (o *SimpleQuery) ToElastic() elastic.Query {
switch o.Key {
case "since":
return elastic.NewRangeQuery("createdAt").From(o.Value)
case "until":
return elastic.NewRangeQuery("createdAt").To(o.Value)
default:
panic("unknown key")
}
}
func main() {
rootQuery, err := parser.ParseString("", "since:2021 AND (since:2023 OR until:2024) AND since:2025")
if err != nil {
panic(err)
}
buf := new(bytes.Buffer)
src, _ := rootQuery.ToElastic().Source()
_ = json.NewEncoder(buf).Encode(src)
println(buf.String())
}