-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamic Parameter Query
76 lines (72 loc) · 1.52 KB
/
Dynamic Parameter Query
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
# define a query template with 2 optional parameters, 0 - 2 could be passed for filtering
# {{#state_p}} {{/state_p}} indicates optional parameter's present
# match_all is here to make json valid, it is like 1=1 in sql to make where clause valid in AND condition.
# depends on situation, match_none could be used, sql equivalent of 1=1, in OR condition
PUT _scripts/dynamic-parm-template
{
"script": {
"lang": "mustache",
"source": """{
"query": {
"bool": {
"filter": [
{{#state_p}} {"term": {"state": "{{state_p}}"}}, {{/state_p}}
{{#zip_p}} {"term": {"zip": "{{zip_p}}"}}, {{/zip_p}}
{ "match_all": {}}
]
}
}
},
"params": {
"state_p": "tx",
"zip_p": "75205"
}
"""
}
}
# response
{
"acknowledged": true
}
# validate template
POST _render/template
{
"id": "dynamic-parm-template",
"params": {
"state_p": "tx",
"zip_p": "75204"
}
}
# response, shows what query looks like after parameter applied
{
"template_output": {
"query": {
"bool": {
"filter": [
{
"term": {
"state": "tx"
}
},
{
"term": {
"zip": "75204"
}
},
{
"match_all": {}
}
]
}
}
}
}
# actual query against ix_state_zip index
GET ix_state_zip/_search/template
{
"id": "dynamic-parm-template",
"params": {
"state_p": "tx",
"zip_p": "75205"
}
}