sarv
sarv
const fs = require("fs").promises;
function joiningFunction(operator) {
if (operator === "AND" || operator === "OR") {
if (lastFilterGroup.should.length > 0) {
filters.push({ bool: { should: lastFilterGroup.should } });
}
if (lastFilterGroup.must.length > 0) {
filters.push({ bool: { must: lastFilterGroup.must } });
}
lastFilterGroup = { must: [], should: [] }; // Reset the filter group
booleanOperator = operator;
} else {
console.error("Unknown joining operator:", operator);
}
}
function nestingFunction(operator) {
if (operator === "AND" || operator === "OR") {
// Push the current filter group onto the stack
filterGroupStack.push({ group: lastFilterGroup, operator: booleanOperator });
function endNesting() {
// Pop the last filter group from the stack
const { group, operator } = filterGroupStack.pop();
const nestedFilter = {
bool: {
[operator === "AND" ? "must" : "should"]: lastFilterGroup[operator ===
"AND" ? "must" : "should"],
},
};
// Return to the previous filter group and add the nested filter
if (booleanOperator === "AND") {
group.must.push(nestedFilter);
} else if (booleanOperator === "OR") {
group.should.push(nestedFilter);
}
if (lastFilterGroup.should.length > 0) {
query.query.bool.must.push({ bool: { should: lastFilterGroup.should } });
}
if (lastFilterGroup.must.length > 0) {
query.query.bool.must.push({ bool: { must: lastFilterGroup.must } });
}
try {
const objectArray = [];
const response = await client.search({
index: index,
scroll: "30m",
body: query,
});
let scrollId = response._scroll_id;
let hits = response.hits.hits;
while (hits.length) {
hits.forEach((doc) => {
objectArray.push(doc._source);
});
scrollId = scrollResponse._scroll_id;
hits = scrollResponse.hits.hits;
}
return objectArray;
} catch (error) {
console.error("Error executing search:", error);
return [];
}
}
function clearFilters() {
filters = [];
lastFilterGroup = { must: [], should: [] };
filterGroupStack = [];
}
(async () => {
// Add filters
addFilter('cities', 'is', ['mumbai'], "OR");
addFilter('cities', 'is', ['bangalore'], 'OR');
joiningFunction("AND");
addFilter('followers', 'is', ['7'], "OR");
nestingFunction("OR");
addFilter('followers', 'is', ['10'], "AND");
addFilter('devId', 'is', ['65c30a240d213691fce25eb7'], "AND");
endNesting(); // End nesting
// Execute search
const results = await search();
await fs.writeFile("results.json", JSON.stringify(results, null, 2));
console.log("Search results written!");
// Clear filters
clearFilters();
})();