From 849ff11bb27950a0d2138172bb6491843583aeb2 Mon Sep 17 00:00:00 2001 From: ferron Date: Mon, 29 Jan 2018 07:04:29 -0400 Subject: [PATCH] fix invalid query nesting functionality bodybuilder now generates valid nested queries fixes #142 fixes #162 --- src/utils.js | 9 +++- test/index.js | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+), 1 deletion(-) diff --git a/src/utils.js b/src/utils.js index 71e5dce..404f920 100644 --- a/src/utils.js +++ b/src/utils.js @@ -134,7 +134,14 @@ export function pushQuery (existing, boolKey, type, ...args) { existing[boolKey].push( {[type]: Object.assign(buildClause(...args), nested.filter.bool)} ) - } else { + } else if ( + type === 'bool' && + _.has(nested, 'query.bool') + ) { + existing[boolKey].push( + {[type]: Object.assign(buildClause(...args), nested.query.bool)} + ) + } else { // Usual case existing[boolKey].push( {[type]: Object.assign(buildClause(...args), nested)} diff --git a/test/index.js b/test/index.js index c46993f..d9c4bfb 100644 --- a/test/index.js +++ b/test/index.js @@ -706,3 +706,125 @@ test('bodybuilder | minimum_should_match query and filter', (t) => { } }) }) + +test('bodybuilder | Nested bool query with must #162', (t) => { + t.plan(1) + + const result = bodyBuilder() + .query('bool', b => b.orQuery('match', 'title', 'Solr').orQuery('match', 'title', 'Elasticsearch')) + .query('match', 'authors', 'clinton gormely') + .notQuery('match', 'authors', 'radu gheorge') + .build() + + t.deepEqual(result, + { + query: { + bool: { + must: [ + { + bool: { + should: [ + { + match: { + title: "Solr" + } + }, + { + match: { + title: "Elasticsearch" + } + } + ] + } + }, + { + match: { + authors: "clinton gormely" + } + } + ], + must_not: [ + { + match: { + authors: "radu gheorge" + } + } + ] + } + } + } +) +}) + +test('bodybuilder | Invalid nested bool query with more "query" #142', (t) => { + t.plan(1) + + const body = bodyBuilder() + + body.query('bool', b => b + .query('term', 'field1', 1) + .query('term', 'field2', 2) + .orQuery('term', 'field3', 3)) + body.query('bool', b => b + .query('term', 'field4', 10) + .query('term', 'field5', 20) + .orQuery('term', 'field6', 30)) + + t.deepEqual(body.build(), + { + query: { + bool: { + must: [ + { + bool: { + must: [ + { + term: { + field1: 1 + } + }, + { + term: { + field2: 2 + } + } + ], + should: [ + { + term: { + field3: 3 + } + } + ] + } + }, + { + bool: { + must: [ + { + term: { + field4: 10 + } + }, + { + term: { + field5: 20 + } + } + ], + should: [ + { + term: { + field6: 30 + } + } + ] + } + } + ] + } + } + } + ) +}) +