Skip to content

Instantly share code, notes, and snippets.

@toniov
Last active August 1, 2017 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toniov/0518991bef2b59f0636c10364714d3dd to your computer and use it in GitHub Desktop.
Save toniov/0518991bef2b59f0636c10364714d3dd to your computer and use it in GitHub Desktop.
JavaScriptでElasticsearchのクエリを作る ref: http://qiita.com/antonvs/items/ae64ca9d4733a8e8341a
{
"bool": {
"must": [{
"term": {
"name": "承太郎"
}
}, {
"match": {
"description": {
"query": "やれやれだぜ"
}
}
}],
"must_not": {
"term": {
"location": "杜王町"
}
}
}
}
const eb = require('es-builder');
const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
host: 'localhost:9200'
});
const query = eb.QueryBuilder()
.query(eb.TermQuery('name', '承太郎'))
.query(eb.MatchQuery('description', 'やれやれだぜ'))
.queryMustNot(eb.TermQuery('location', '杜王町'));
JSON.stringify(query);
// {
// "bool": {
// "must": [{
// "term": {
// ...
// ...
// }
// }
client.search({
index: 'user',
type: 'stand_user',
body: {
query: query
}
}, function(err, resp) {
// result of the search here
...
});
const eb = require('es-builder');
const query = eb.QueryBuilder();
// フィルターを追加する
query
.filter(eb.TermsQuery('name', ['ジョセフ', 'ジョナサン']))
.filter(eb.ExistsQuery('age'));
// bool queryを作る
const boolQuery = eb.BoolQuery()
.should(eb.RangeQuery('age').gt(20).lt(40))
.should(eb.PrefixQuery('surname', 'ジョ'));
// ネストする
query.filter(boolQuery);
// queryインスタンスはstringifyすると
// JSON.stringify(query)
// {
// "bool": {
// "filter": {
// bool: {
// "must": [{
// "terms": {
// "name": {
// "value": ["ジョセフ", "ジョナサン"]
// }
// }
// }, {
// "exists": {
// "field": "age"
// }
// }, {
// "bool": {
// "should": [{
// "range": {
// "age": { "gt": 20, "lt": 40 }
// }
// }, {
// "prefix": {
// "surname": {
// "value": "ジョ"
// }
// }
// }]
// }
// }]
// }
// }
// }
// }
$ npm install -g es-builder
...
$ es-builder
es-builder> query = QueryBuilder().query(TermQuery('name', 'カービィ')).query(MatchQuery('description', 'まるくて、ふわふわしてる')).queryMustNot(TermQuery('name', 'ワドルディ'));
es-builder> query.stringified
'{"bool":{"must":[{"term":{"name":{"value":"カービィ"}}},{"match":{"description":{"query":"まるくて、ふわふわしてる"}}}],"must_not":{"term":{"name":{"value":"ワドルディ"}}}}}'
es-builder> .exit
$ curl -XGET 'http://localhost:9200/games/dreamland/_search' -d'
{
"query" : {"bool":{"must":[{"term":{"name":{"value":"カービィ"}}},{"match":{"description":{"query":"まるくて、ふわふわしてる"}}}],"must_not":{"term":{"name":{"value":"ワドルディ"}}}}}
}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment