Elasticsearch v6.0.1 Nodejs boost match with one of arrays elements - javascript

In my project I have user objects like this.
{
"_id": "1",
"username": "RAggro",
"name": "Vardan Tadevosyan"
},
{
"_id": "2",
"username": "XACHIK",
"name": "XACHIK"
},
{
"_id": "3",
"username": "vardar",
"name": "Vardan Gukoyan"
},
{
"_id": "4",
"username": "Gordey",
"name": "Gordey Gordeev"
},
{
"_id": "5",
"username": "id220107973",
"name": "Vardan Ayvazyan"
},
{
"_id": "6",
"username": "vvardanyan4",
"name": "Vardan Vardanyan"
},
{
"_id": "7",
"username": "svardan",
"name": "Vardan Sargsyan"
}
And I have list of _id-s, like [51,3,9,11,6, 2].
I whant to query users by 'name' and 'username', orderid like first comes users that contains in ids array then others
query: {
multi_match: {
query: "vardan",
fields: ["name", "username"],
operator: "or"
},
boosting: {
positive: {
term: {
_id: [51,3,9,11,6, 2]
}
},
positive_boost: 2.0
}
}
So the expected result is:
{
"_id": "3",
"username": "vardar",
"name": "Vardan Gukoyan"
},
{
"_id": "6",
"username": "vvardanyan4",
"name": "Vardan Vardanyan"
},
{
"_id": "1",
"username": "RAggro",
"name": "Vardan Tadevosyan"
},
{
"_id": "5",
"username": "id220107973",
"name": "Vardan Ayvazyan"
},
{
"_id": "7",
"username": "svardan",
"name": "Vardan Sargsyan"
}
But I'm fetching empty array,
Please, help how can I modify my query to reach expected ordered result.

You can do it easily using a bool/should clause that will boost the documents whose IDs are within the specified group:
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "vardan",
"fields": [
"name",
"username"
],
"operator": "or"
}
}
],
"should": [
{
"ids": {
"values": ["51","3","9","11","6","2"]
}
}
]
}
}
}

It works using this query:
{
query:{
"bool": {
"must": [{
"multi_match": {
"query": "vardan",
"fields": [
"name",
"username"
],
"operator": "or"
}
}],
"should": [{
"terms": {
"_id": ["51","3","9","11","6","2"],
"boost": 100
}
}]
}
}
}

Related

How to return single object (mongoose/mongoDB)

I have this data stored in database.
{
"_id": "62fa5aa25778ec97bc6ee231",
"user": "62f0eb5ebebd0f236abcaf9d",
"name": "Marketing Plan",
"columns": [
{
"name": "todo",
"_id": "62fa5aa25778ec97bc6ee233",
"tasks": [
{
"title": "Task Four testing 2",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes test",
"completed": false,
"_id": "62ff74bfe80b11ade2d34456"
},
{
"name": "do homework",
"completed": false,
"_id": "62ff74bfe80b11ade2d34457"
}
],
"_id": "62ff74bfe80b11ade2d34455"
}
]
},
{
"name": "doing",
"_id": "62fa5aa25778ec97bc6ee234",
"tasks": []
},
{
"name": "done",
"_id": "62fa5aa25778ec97bc6ee235",
"tasks": []
}
],
"__v":0
}
I want to be able to return a single object with the id equal to the req.params.id, in this case that would be 62ff74bfe80b11ade2d34455.
{
"title": "Task Four testing 2",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes test",
"completed": false,
"_id": "62ff74bfe80b11ade2d34456"
},
{
"name": "do homework",
"completed": false,
"_id": "62ff74bfe80b11ade2d34457"
}
],
"_id": "62ff74bfe80b11ade2d34455"
}
I researched stackoverflow and came across this potential solution: Mongoose retrieve one document from nested array which implemented the aggregate framework. But when I test this in postman, the request isn't made.
const getTask = asyncHandler(async (req, res) => {
const task = await Board.aggregate([
{
$match: {
"columns.tasks._id": req.params.id,
},
},
{
$project: {
columns: {
$first: {
$filter: {
input: "$columns.tasks",
cond: {
$eq: ["$$this._id", req.params.id],
},
},
},
},
},
},
{
$replaceRoot: {
newRoot: "$columns",
},
},
]);
});
Having an array inside an array complicates the query a bit, but here's one way to retrieve the data you want.
db.Board.aggregate([
{
$match: {
"columns.tasks._id": req.params.id
}
},
{"$unwind": "$columns"},
{
$match: {
"columns.tasks._id": req.params.id
}
},
{
"$project": {
"task": {
"$first": {
"$filter": {
"input": "$columns.tasks",
"cond": {"$eq": ["$$this._id", req.params.id]}
}
}
}
}
},
{"$replaceWith": "$task"}
])
Try it on mongoplayground.net. [The mongoplayground.net example uses "62ff74bfe80b11ade2d34455" rather than req.params.id.]

MongoDB query to get top selling products

I have a MongoDB collection "orders" with document similar to such:
{
"_id": ObjectId("xxxxx"),
"orderNo": 0,
"products": [
{ "product1": ["_Id": objectId("eeee"),"productName", "quantity", "price"] },
{ "product2": ["_Id": objectId("ffff"),"productName", "quantity", "price"] }
],
"deliveryAddress": "addsfdfghf"
}
{
"_id": ObjectId("yyyyy"),
"orderNo": 1,
"products": [
{ "product1": ["_Id": objectId("dddd"),"productName", "quantity", "price"] }
],
"deliveryAddress": "rwetrutytyi"
}
{
"_id": ObjectId("zzzz"),
"orderNo": 2,
"products": [
{ "product1": ["_Id": objectId("aaaa"), "productName", "quantity", "price"] },
{ "product2": ["_Id": objectId("bbbb"),"productName", "quantity", "price"] },
{ "product3": ["_Id": objectId("cccc"),"productName", "quantity", "price"] }
],
"deliveryAddress": "rwetrutytyi"
}
Now I want to write a query to get top selling products using "quantity" property of every products.
correct values of in above document look like:
{
"products": [{
"_id": {
"$oid": "612baf1b89c77b25c40aa3bc"
},
"productID": "NPZ6I",
"productName": "Cosentys 150ml",
"quantity": "1",
"expireDate": "04/20/2022",
"price": "22200"
}, {
"_id": {
"$oid": "612baf1b89c77b25c40aa3bb"
},
"productID": "NPZ3I",
"productName": "Asunra 400mg",
"quantity": "2",
"expireDate": "09/26/2021",
"price": "13200"
}],
"orderNo": 9,
"deliveryAddress": "Dhaka"
}
I want to return an object look like:
{
"_id": ObjectId("yyyyy"),
"productName": "String",
"productID": "String",
"totalSales" : "Number(sum of each products quantity)",
"totalEarning": "Number(sum of each product's price)"
}

Give document fields different priority in ElasticSearch

I have data:
{"NAME": "BRIDGE CAMBODJA", "NAME": "CAMBRIDGE APARTMENTS", "NAME":"KULAMAN BRIDGE"}
I have the following query:
'{"query": {"query_string": {"query": "BRIDGE"}'
and I want what will appear is:
{"NAME": "BRIDGE CAMBODJA", "NAME": "KULAMAN BRIDGE", "NAME": "CAMBRIDGE APARTMENTS"}
How do I modify my search to set the field ranking / priority?
You can achieve your required result, by using the boost parameter directly in the query and querying for NAME which begins with BRIDGE, ends with BRIDGE, or which contains BRIDGE.
Adding a working example
Index Mapping:
{
"mappings": {
"properties": {
"NAME": {
"type": "keyword"
}
}
}
}
Search Query:
{
"query": {
"bool": {
"should": [
{
"query_string": {
"default_field": "NAME",
"query": "BRIDGE*",
"boost": 10
}
},
{
"query_string": {
"default_field": "NAME",
"query": "*BRIDGE",
"boost": 5
}
},
{
"query_string": {
"default_field": "NAME",
"query": "*BRIDGE*",
"boost": 1
}
}
]
}
}
}
Search Result:
"hits": [
{
"_index": "66095448",
"_type": "_doc",
"_id": "1",
"_score": 11.0,
"_source": {
"NAME": "BRIDGE CAMBODJA"
}
},
{
"_index": "66095448",
"_type": "_doc",
"_id": "3",
"_score": 6.0,
"_source": {
"NAME": "KULAMAN BRIDGE"
}
},
{
"_index": "66095448",
"_type": "_doc",
"_id": "2",
"_score": 1.0,
"_source": {
"NAME": "CAMBRIDGE APARTMENTS"
}
}
]

Nested Should query(OR) inside a Must query(AND) in elastic Search

I have elastic Search data in following format:
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "stellenbosch" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
},
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "Rustenburg" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
},
{
"is_cricketer": 0,
"name": "deVilliers",
"cities": [
{ "name": "Cape town" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
I need to query elastic search to get all the profiles with is_cricketer = 1 and an OR query over the field for cities.name and name field. ie
( profile.is_cricketer == 1 && (profile.name == 'Abraham' || profile.cities[i].name == 'Nelspruit' ))
To get the profiles with OR query on the fields cities.name and name field for matching query string is as follows and it works a expected:
"should": [
{
"nested": {
"path": "cities",
"query": {
"multi_match": {
"query": "Nelspruit",
"fields": [
"cities.name"
]
}
}
}
},
{
"multi_match": {
"query": "Abraham",
"fields": [
"name"
]
}
}
]
And the Must query to get all the profiles with field is_cricketer = 1 is follows:
{
"must": {
"match": {
"is_cricketer": "1"
}
}
}
Above both queries working fine and i am trying to combine both query as follows:
{
"query": {
"bool": {
"must": {
"match": {
"is_cricketer": "1"
}
},
"should": [
{
"nested": {
"path": "cities",
"query": {
"multi_match": {
"query": "Nelspruit",
"fields": [
"cities.name"
]
}
}
}
},
{
"multi_match": {
"query": "Abraham",
"fields": [
"name"
]
}
}
]
}
}
}
which is not returning expected results, its returning all the profiles with is_cricketer = 1 without filtering for name and cities.name.
I also tried to include the should query inside must query as follows:
{
"query": {
"bool": {
"must": [{
"match": {
"is_cricketer": "1"
}
}, {
"should": [
{
"nested": {
"path": "cities",
"query": {
"multi_match": {
"query": "Nelspruit",
"fields": [
"cities.name"
]
}
}
}
},
{
"multi_match": {
"query": "Abraham",
"fields": [
"name"
]
}
}
]
}]
}
}
}
But i got following error for the above query:
"Error: [parsing_exception] [should] query malformed, no start_object
after query name, with { line=1 & col=64 }
at respond (/GitRepo/project/node_modules/elasticsearch/src/lib/transport.js:307:15)
at checkRespForFailure (/GitRepo/project/node_modules/elasticsearch/src/lib/transport.js:266:7)
at HttpConnector. (/GitRepo/project/node_modules/elasticsearch/src/lib/connectors/http.js:159:7)
at IncomingMessage.bound (/GitRepo/project/node_modules/elasticsearch/node_modules/lodash/dist/lodash.js:729:21)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)"
How to combine both the queries to get desired result. Any help will be appreciated.
if you want a should query inside a must you can use it in the following way
{
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
... your query here
}
]
}
}
]
}
}
}
This worked for me on ES 6.0.
Setup
PUT test1
{
"mappings": {
"type1": {
"properties": {
"cities": {
"type": "nested"
}
}
}
}
}
POST test1/type1
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "stellenbosch" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
POST test1/type1
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "Rustenburg" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
POST test1/type1
{
"is_cricketer": 0,
"name": "deVilliers",
"cities": [
{ "name": "Cape town" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
Query
GET test1/type1/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"is_cricketer": {
"value": 1
}
}
}
],
"should": [
{
"term": {
"name.keyword": {
"value": "Abraham"
}
}
},
{
"nested": {
"path": "cities",
"query": {
"term": {
"cities.name.keyword": {
"value": "Nelspruit"
}
}
}
}
}
]
}
}
}
Results - 2 hits
"hits": {
"total": 2,
"max_score": 2.2685113,
"hits": [
{
"_index": "test1",
"_type": "type1",
"_id": "zgcesWIBVwCaLf8KSuDi",
"_score": 2.2685113,
"_source": {
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{
"name": "stellenbosch"
},
{
"name": "Nelspruit"
},
{
"name": "East London"
}
]
}
},
{
"_index": "test1",
"_type": "type1",
"_id": "eAQesWIBbxh35CpKckEH",
"_score": 2.2685113,
"_source": {
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{
"name": "Rustenburg"
},
{
"name": "Nelspruit"
},
{
"name": "East London"
}
]
}
}
]
}

How we remove full object of array from array of object using JavaScript or lodash?

My JSON looks like this:
{
"success": true,
"data": [
{
"user": {
"firstname": "demo",
test1": {
"role": {
"name": "demo"
},
"status": "pending",
"test2": {
"telephone": "+demo"
}
}
},
"authData": [
{
"_key": "demo",
"_id": "demo",
}
]
}
],
"session": {
"_key": "demo",
"uid": "demo",
}
}
I want to remove authData array from JSON.
First your JSON is invalid. This is corrected version:
{
"success": true,
"data": [
{
"user": {
"firstname": "demo",
"test1": {
"role": {
"name": "demo"
},
"status": "pending",
"test2": {
"telephone": "+demo"
}
}
},
"authData": [
{
"_key": "demo",
"_id": "demo"
}
]
}
],
"session": {
"_key": "demo",
"uid": "demo"
}
}
Now you can use DELETE operator to delete your key.

Categories

Resources