Skip to content

Instantly share code, notes, and snippets.

@jpotts
Last active August 22, 2020 01:39
Show Gist options
  • Save jpotts/48e42e35bc64be9a203e to your computer and use it in GitHub Desktop.
Save jpotts/48e42e35bc64be9a203e to your computer and use it in GitHub Desktop.
Code snippets that go along with an ecmarchitect.com blog post on Elasticsearch search templates.
POST /_search/template/tweets
{
"template": {
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"term": {
"message": "{{ search_term }}"
}
}
]
}
}
}
}
}
}
POST /twitter/tweet/_search/template
{
"file": "tweets",
"params": {
"search_term": "elasticsearch"
}
}
POST /twitter/tweet/_search/template
{
"id": "tweets",
"params": {
"search_term": "elasticsearch"
}
}
POST /twitter/tweet/_search/template
{
"file": "tweets",
"params": {
"search_term": "elasticsearch",
"since": "now-30d"
}
}
Map<String, Object> params = new HashMap<String, Object>();
params.put("search_term", "elasticsearch");
params.put("since", "now-30d");
Template template = new Template("tweets", ScriptService.ScriptType.FILE, MustacheScriptEngineService.NAME, null, params);
SearchRequestBuilder request = client.prepareSearch(INDEX).setTemplate(template);
SearchResponse response = request.execute().actionGet();
{
"search_term": "elasticsearch",
"since": "now-30d",
"userList": {
"users": [
{
"name": "elastic"
},
{
"name": "jeffpotts01",
"isLast": true
}
]
}
}
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [{
"and": [{
"term": {
"message": "elasticsearch"
}
}, {
"range": {
"@timestamp": {
"gte": "now-30d"
}
}
}, {
"or": [{
"term": {
"user": "elastic"
}
}, {
"term": {
"user": "jeffpotts01"
}
}]
}]
}]
}
}
}
}
}
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"and": [
{
"term": {
"message": "{{ search_term }}"
}
}
{{#since}}
,
{
"range": {
"@timestamp": {
"gte": "{{ since }}"
}
}
}
{{/since}}
{{#userList}}
,
{
"or": [
{{#users}}
{
"term": {
"user": "{{ name }}"
}
}
{{^isLast}},{{/isLast}}
{{/users}}
]
}
{{/userList}}
]
}
]
}
}
}
}
}
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"and": [
{
"term": {
"message": "{{ search_term }}"
}
}
{{#since}}
,
{
"range": {
"@timestamp": {
"gte": "{{ since }}"
}
}
}
{{/since}}
{{^since}}
,
{
"range": {
"@timestamp": {
"gte": "now-1d"
}
}
}
{{/since}}
]
}
]
}
}
}
}
}
POST /twitter/tweet/_search/template
{
"inline": {
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"term": {
"message": "{{ search_term }}"
}
}
]
}
}
}
}
},
"params": {
"search_term": "elasticsearch"
}
}
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"and": [
{
"term": {
"message": "{{ search_term }}"
}
}
{{#since}}
,
{
"range": {
"@timestamp": {
"gte": "{{ since }}"
}
}
}
{{/since}}
]
}
]
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment