How to index multidimensional arrays in couchdb

ⅰ亾dé卋堺 提交于 2019-12-06 04:09:25
brobes

This is a lot like my response at Cloudant Selector Query but here's the deal, applied to your question:

The easiest way to run this query is using "Cloudant Query" (or "Mango", as it's called in the forthcoming CouchDB 2.0 release) -- and not the traditional MapReduce view indexing system in CouchDB. (This blog covers the differences: https://cloudant.com/blog/mango-json-vs-text-indexes/ and this one is an overview: https://developer.ibm.com/clouddataservices/2015/11/24/cloudant-query-json-index-arrays/).

Here's what your CQ index should look like:

{
  "index": {
    "fields": [
      {"name": "Teams.[].id", "type": "string"}
    ]
  },
  "type": "text"
}

And what the subsequent query looks like:

{
  "selector": {
    "Teams": {"$elemMatch": {"id": "79d25d41d991890350af672e0b76faed"}}
  },
  "fields": [
    "_id",
    "FirstName",
    "LastName"
  ]
}

You can try it yourself in the "Query" section of the Cloudant dashboard or via curl with something like this:

curl -H "Content-Type: application/json" -X POST -d '{"selector":{"Teams":{"$elemMatch":{"id":"79d25d41d991890350af672e0b76faed"}}},"fields":["_id","FirstName","LastName"]}' https://broberg.cloudant.com/teams_test/_find

That database is world-readable, so you can see the sample documents I created in there here: https://broberg.cloudant.com/teams_test/_all_docs?include_docs=true

Dig the Seinfeld theme :D

You simply need to loop through the Teams array and emit a view entry for each of the teams.

function (doc) {
  if(doc.Kind === "Profile"){
    for (var i=0; i<doc.Teams.length; i++) {
      var team = doc.Teams[i];
      emit(team.id, [doc.FirstName, doc.LastName]);
    }
  }
}

You can then query for all profiles with a specific team id by keying on the team id like this

.../view?key="79d25d41d991890350af672e0b76faed"

giving

{"total_rows":7,"offset":2,"rows":[
{"id":"0d15041f43b43ae07e8faa737f00032c","key":"79d25d41d991890350af672e0b76faed","value":["Adam","Alpha"]},
{"id":"68779729be3610fd8b52b22574000ae8","key":"79d25d41d991890350af672e0b76faed","value":["Bob","Bravo"]},
{"id":"9f97f1565f03aebae9ca73e207001ee1","key":"79d25d41d991890350af672e0b76faed","value":["Chuck","Charlie"]}
]}

or you can include the actual profiles in the result by adding &include_docs=true to the query.

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