Skip to content

Commit 849ff11

Browse files
committed
fix invalid query nesting functionality
bodybuilder now generates valid nested queries fixes #142 fixes #162
1 parent f14b245 commit 849ff11

File tree

2 files changed

+130
-1
lines changed

2 files changed

+130
-1
lines changed

src/utils.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,14 @@ export function pushQuery (existing, boolKey, type, ...args) {
134134
existing[boolKey].push(
135135
{[type]: Object.assign(buildClause(...args), nested.filter.bool)}
136136
)
137-
} else {
137+
} else if (
138+
type === 'bool' &&
139+
_.has(nested, 'query.bool')
140+
) {
141+
existing[boolKey].push(
142+
{[type]: Object.assign(buildClause(...args), nested.query.bool)}
143+
)
144+
} else {
138145
// Usual case
139146
existing[boolKey].push(
140147
{[type]: Object.assign(buildClause(...args), nested)}

test/index.js

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,3 +706,125 @@ test('bodybuilder | minimum_should_match query and filter', (t) => {
706706
}
707707
})
708708
})
709+
710+
test('bodybuilder | Nested bool query with must #162', (t) => {
711+
t.plan(1)
712+
713+
const result = bodyBuilder()
714+
.query('bool', b => b.orQuery('match', 'title', 'Solr').orQuery('match', 'title', 'Elasticsearch'))
715+
.query('match', 'authors', 'clinton gormely')
716+
.notQuery('match', 'authors', 'radu gheorge')
717+
.build()
718+
719+
t.deepEqual(result,
720+
{
721+
query: {
722+
bool: {
723+
must: [
724+
{
725+
bool: {
726+
should: [
727+
{
728+
match: {
729+
title: "Solr"
730+
}
731+
},
732+
{
733+
match: {
734+
title: "Elasticsearch"
735+
}
736+
}
737+
]
738+
}
739+
},
740+
{
741+
match: {
742+
authors: "clinton gormely"
743+
}
744+
}
745+
],
746+
must_not: [
747+
{
748+
match: {
749+
authors: "radu gheorge"
750+
}
751+
}
752+
]
753+
}
754+
}
755+
}
756+
)
757+
})
758+
759+
test('bodybuilder | Invalid nested bool query with more "query" #142', (t) => {
760+
t.plan(1)
761+
762+
const body = bodyBuilder()
763+
764+
body.query('bool', b => b
765+
.query('term', 'field1', 1)
766+
.query('term', 'field2', 2)
767+
.orQuery('term', 'field3', 3))
768+
body.query('bool', b => b
769+
.query('term', 'field4', 10)
770+
.query('term', 'field5', 20)
771+
.orQuery('term', 'field6', 30))
772+
773+
t.deepEqual(body.build(),
774+
{
775+
query: {
776+
bool: {
777+
must: [
778+
{
779+
bool: {
780+
must: [
781+
{
782+
term: {
783+
field1: 1
784+
}
785+
},
786+
{
787+
term: {
788+
field2: 2
789+
}
790+
}
791+
],
792+
should: [
793+
{
794+
term: {
795+
field3: 3
796+
}
797+
}
798+
]
799+
}
800+
},
801+
{
802+
bool: {
803+
must: [
804+
{
805+
term: {
806+
field4: 10
807+
}
808+
},
809+
{
810+
term: {
811+
field5: 20
812+
}
813+
}
814+
],
815+
should: [
816+
{
817+
term: {
818+
field6: 30
819+
}
820+
}
821+
]
822+
}
823+
}
824+
]
825+
}
826+
}
827+
}
828+
)
829+
})
830+

0 commit comments

Comments
 (0)