index and query items in an array with mango query for cloudant and couchdb 2.0

ⅰ亾dé卋堺 提交于 2019-12-23 02:23:04

问题


I have the following db structure:

{"_id": "0096874","genre": ["Adventure","Comedy", "Sci-Fi" ]}
{"_id": "0099088","genre": ["Comedy", "Sci-Fi", "Western"]}

and like to query it like I could do in mongodb

db.movies.find({genre: {$in: ["Comedy"]}})

It works when i use a text index for the whole database, but that seems very wasteful:

// index
    {
      "index": {},
      "type": "text"
    }
//query
{
  "selector": {
    "genre": {
      "$in": ["Comedy"]
    }
  },
  "fields": [
    "_id",
    "genre"
  ]
}

The following index does not work:

{
  "index": {
    "fields": [
      "genre"
    ]
  },
  "type": "json"
}

What is the correct index for cloudant query, which does not index the whole db? Thanks for your help


回答1:


You had it almost correct. Your index is right, but you need to throw in a selector to get all IDs https://cloudant.com/blog/mango-json-vs-text-indexes/.

This isn't a great solution performance-wise, as Tony says,

The reason this works is, again, because Mango performs the above $in operation as a filtering mechanism against all the documents. As we saw in the conclusion of the previous section on JSON syntax, the performance tradeoff with the query above is that it, essentially, performs a full index scan and then applies a filter.

{
  "selector": {
    "_id": {
      "$gt": null
    }, 
    "genre": {
      "$in": ["Western"]
    }
  },
  "fields": [
    "_id",
    "genre"
  ],
  "sort": [
    {
      "_id": "asc"
    }
  ]
}


来源:https://stackoverflow.com/questions/34107333/index-and-query-items-in-an-array-with-mango-query-for-cloudant-and-couchdb-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!