![](/img/trans.png)
[英]How to find matching elements from an array of objects using mongoDB query
[英]Remove elements/objects From Array in ElasticSearch Followed by Matching Query
我有以下類型的文件。
{
"_index": "example1",
"_type": "doc",
"_id": "8036",
"_score": 1,
"_source": {
"user": "kimchy8036",
"postDate": "2009-11-15T13:12:00",
"locations": [
[
72.79887719999999,
21.193036000000003
],
[
-1.8262150000000001,
51.178881999999994
]
]
}
}
下面是映射:
{
"example1": {
"mappings": {
"doc": {
"properties": {
"locations": {
"type": "geo_point"
},
"postDate": {
"type": "date"
},
"status": {
"type": "long"
},
"user": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
我可以使用以下查詢添加多個位置。
POST /example1/_update_by_query
{
"query": {
"match": {
"_id": "3"
}
},
"script" : {
"lang":"painless",
"inline": "ctx._source.locations.add(params.newsupp)",
"params":{
"newsupp":[-74.00,41.12121 ]
}}
}
但無法從位置刪除數組對象。 我試過下面的查詢但工作。 POST 示例 1/doc/3/_update {
"script" :
{
"lang":"painless",
"inline":"ctx._source.locations.remove(params.tag)",
"params":{
"tag":[-74.00,41.12121]
}
}
}
請讓我知道我在這里做錯了什么。 我使用的是彈性版本 5.5.2
與add()
不同, remove()
獲取元素的索引並將其刪除。
你的ctx._source.locations
是一個ArrayList
。 它有List
的remove()
方法:
E 刪除(整數索引)
移除此列表中指定位置的元素(可選操作)。 ...
有關其他方法,請參閱無痛 API - 列表。
有關示例代碼,請參閱此答案。
在無痛腳本中, Array.remove()
方法按索引而不是按值刪除。
這是一個在 Elasticsearch 腳本中按值刪除數組元素的工作示例:
POST objects/_update_by_query
{
"query": {
... // use regular ES query to remove only in relevant documents
},
"script": {
"source": """
if (ctx._source[params.array_attribute] != null) {
for (int i=ctx._source[params.array_attribute].length-1; i>=0; i--) {
if (ctx._source[params.array_attribute][i] == params.value_to_remove) {
ctx._source[params.array_attribute].remove(i);
}
}
}
""",
"params": {
"array_attribute": "<NAME_OF_ARRAY_PROPERTY_TO_REMOVE_VALUE_IN>",
"value_to_remove": "<VALUE_TO_REMOVE_FROM_ARRAY>",
}
}
}
如果您的腳本只從一個特定的數組屬性中刪除值,您可能想要簡化腳本。 例如,從文檔的.color_list
數組中刪除"green"
:
_doc/001 = {
"color_list": ["red", "blue", "green"]
}
刪除"green"
腳本:
POST objects/_update_by_query
{
"query": {
... // use regular ES query to remove only in relevant documents
},
"script": {
"source": """
for (int i=ctx._source.color_list.length-1; i>=0; i--) {
if (ctx._source.color_list[i] == params.color_to_remove) {
ctx._source.color_list.remove(i);
}
}
""",
"params": {
"color_to_remove": "green"
}
}
}
"script" : {
"lang":"painless",
"inline":"ctx._source.locations.remove(params.tag)",
"params":{
"tag":indexToRemove
}
}
如果使用ctx._source.locations.add(elt)
添加元素,使用ctx._source.locations.remove(indexToRemove)
,則通過數組中元素的索引刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.