Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mysql - can couchdb do loops

Can couchdb do loops?

Let's say I have a database of interests that have 3 fields subject1,subject2,subject3. example, cats,nutrition,hair or space,telescopes,optics etc.

A person (A) has 10 interests composed of 3 fields each.

10 more people B,C,D...have 10 interests each composed of 3 subjects each.

When person A logs in I want the system to search for all people with matching interests.

In javascript I would normally loop through all the interests and then find matching ones I guess using two loops. Then store the matches in another database for the user like "matchinginterests".

Is there any easy way to do this in couchdb compared to mysql -- which seems very complicated.

Thanks, Dan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think I understand what you are asking. The answer is pretty straightforward with Map/Reduce.

Say you have the following people documents:

{
   "name": "Person A",
   "interests" [ "computers", "fishing", "sports" ]
}
{
   "name": "Person B",
   "interests" [ "computers", "gaming" ]
}
{
   "name": "Person C",
   "interests" [ "hiking", "sports" ]
}
{
   "name": "Person D",
   "interests" [ "gaming" ]
}

You would probably want to emit your key as the interest, with the value as the person's name (or _id).

function (doc) {
   for (var x = 0, len = doc.interests.length; x < len; x++) {
      emit(doc.interests[x], doc..name);
   }
}

Your view results would look like this:

  • computers => Person A
  • computers => Person B
  • fishing => Person A
  • gaming => Person B
  • gaming => Person D
  • hiking => Person C
  • sports => Person A
  • sports => Person C

To get a list of people with computers as an interest, you can simply send key="computers" as part of the query string.

If you want to add a reduce function to your map, you can simply use _count (shortcut to use a compiled reduce function) and you can retrieve a count of all the people with a particular interest, you can even use that to limit which interests you query to build your relationships.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...