开发者

Find the most similarity between a group of attributes (mongodb)

I have a database in the following syntax:

{_id:'342', values:{ A: '432', B: 'asdf', C: '23', D: 'gg'}}
{_id:'343', values:{ A: 's', B: 'fsd', C: 'as', D: '4'}}
{_id:'344', values:{ A: 'f', B: 'f', C: 'af', D: '32'}}
{_id:'345', values:{ A: 'f', B: 'f', C: '333', D开发者_开发问答: 'adf'}}

Given a set of values for A, B, C, D - I want to find the document that has the most similarities.

e.g.

Given, {values: {A: 'f', B: 'f', C: '333', D: '832'}} it will match _id: 345 because it has A, B, and C matching.

I want to get the results that are most similar to the values I have.

Is there a query/algorithm that could accomplish this fast?

Note: Wasn't sure how to title this, if you have a better title feel free to edit it.


Here's one way you could do it, assuming you want the results in order of closeness to matching and assuming that there are just 4 (so it's feasible to do all permutations):

Use $elemMatch (see http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24elemMatch) repeatedly.

First query for all 4 values (1 query).
If that fails query for each combination of 3 values (4 queries).
If that fails query for each combination of 2 values (6 queries).
If that fails query for just one match (4 queries).

An alternative would be to use map reduce. In the map function calculate the score for a row, if the score is > 0 emit the document id as the key and the score as the value. In the reduce phase pass through the single result without any work on it. Sort the results by score.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜