【问题标题】:Return Percentage of Matches between Array Comparison返回数组比较之间匹配的百分比
【发布时间】:2017-08-01 16:50:34
【问题描述】:

我有一个包含大量数据的 mongodb 存储库,我需要在给定输入的情况下搜索和分类数据。

我计划有一个服务器来处理请求并给出响应,但我不确定要使用哪种算法、大数据工具甚至 mongodb 命令。

这是我需要做的一个例子。

我有这个数据库:

[
    {
        id: 1,
        Colors: ["Green","Red","Blue","Yellow"]
    },
    {
        id: 2,
        Colors: ["Green","Red","Blue"]
    },
    {
        id: 3,
        Colors: ["Green","Red"]
    },
    {
        id: 4,
        Colors: ["Green"]
    }
]

然后我有这个输入

String x = "Green Red" 

或类似 JSON 的

 { Colors: ["Green","Red"]}

然后它会返回匹配这个输入的数据:

[
    {
        id: 4,
        Colors: ["Green"],
        Matches: 100%
    }
    {
        id: 3,
        Colors: ["Green","Red"],
        Matches: 100%
    },
    {
        id: 2,
        Colors: ["Green","Red","Blue"],
        Matches: 66%
    },
    {
        id: 1
        Colors: ["Green","Red","Blue","Yellow"],
        Matches: 50%
    }
]

【问题讨论】:

  • 您认为提供的答案中是否有某些内容无法解决您的问题?如果是这样,那么请对答案发表评论,以澄清究竟需要解决哪些尚未解决的问题。如果它确实回答了您提出的问题,请注意Accept your Answers您提出的问题

标签: mongodb mongodb-query aggregation-framework bigdata


【解决方案1】:

简单来说,您希望$filter 来自源输入的正匹配数组,然后将生成的$size 与原始值进行比较。不同版本的技术略有不同,但基本上:

db.getCollection('junk').aggregate([
  { "$addFields": {
    "Matches": {
      "$trunc": {
        "$multiply": [
          { "$divide": [
            { "$size": {
              "$filter": {
                "input": "$Colors",
                "as": "c",
                "cond": { "$in": [ "$$c", ["Green","Red"] ] }
              }
            }}, 
            { "$size": "$Colors" }
          ]},
          100
        ]
      }
    }
  }}
])

只要比较值和数组都包含“唯一”元素,您就可以使用$setIntersection 而不是使用$filter

db.getCollection('junk').aggregate([
  { "$addFields": {
    "Matches": {
      "$trunc": {
        "$multiply": [
          { "$divide": [
            { "$size": {
                "$setIntersection": [ "$Colors", ["Green", "Red"] ] 
            }}, 
            { "$size": "$Colors" }
          ]},
          100
        ]
      }
    }
  }}
])

如果您没有$trunc$floor,您可以使用$mod$subtract 进行数学运算以丢弃剩余部分:

db.getCollection('junk').aggregate([
  { "$project": {
    "id": 1,
    "Colors": 1,
    "Matches": {
      "$let": {
        "vars": {
          "perc": {
            "$multiply": [
              { "$divide": [
                { "$size": {
                    "$setIntersection": [ "$Colors", ["Green", "Red"] ] 
                }}, 
                { "$size": "$Colors" }
              ]},
              100
            ]
          }
        },
        "in": {
          "$subtract": [ "$$perc", { "$mod": [ "$$perc", 1 ] } ]      
        }
      }
    }
  }}
])

但通常保持相同的原则。

“匹配的数量除以数组的总长度等于匹配的百分比”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 2011-09-29
    • 2020-06-18
    • 2019-10-30
    • 2020-02-08
    相关资源
    最近更新 更多