As I delve into constructing elasticsearch queries, I find myself eager to implement object templates to simplify the creation of POST bodies for my queries before they are sent to the data service.
Although the initial query construction goes smoothly, I encounter a challenge when using templates. It seems that the const objects I declare are being altered, causing the template to malfunction thereafter. In the snippet below, not only is the returnQuery value modified, but the INIT_QUERY const also experiences the same issue. Is there a way to utilize this const object as a template without actually changing its value?
const INIT_QUERY = {
"query": {
"filtered": {
"filter": {
"bool": {
"must": <any>[]
}
}
}
}
}
const MATCH_QUERY = {
"match": <any>{}
}
...
export class QueryBuilder {
constructor() {}
buildQuery() {
let returnQuery = INIT_QUERY;
.... loop
let query = MATCH_QUERY;
query.match[dbfield].query = 'fieldValueToSearch';
returnQuery.query.filtered.filter.bool.must.push(query);
.... end loop
return returnQuery;
}
}