查询自定义客户数据的最佳方法是什么。 MongoDB / ElasticSearch

时间:2013-03-12 21:38:38

标签: mongodb full-text-search elasticsearch

我正在做一个客户可以发送自定义数据的应用程序,这个自定义数据应该是“可查询的”,我的意思是客户可以搜索这些字段。

以下用户发送的数据:

data = {
  name: "Thiago",
  id: 2093  
  country: "Portugal",
  custom_data: {
    company: "foo",
     plan: "pro",
     department: "it",
     sessions: 203 
  }
}

由于应用程序方案要求较低,我们使用mongoDB来保存数据。

但是,我想知道如何查询这些自定义数据?我们没有这些字段的索引,并且有很多文档~1.3M。

我认为使用elasticsearch我们可以处理这个要求,但有没有使用它的好方法?只使用mongodb?

一个查询示例可能是:

  

查找来自葡萄牙的所有内容,并且有超过100次登录。

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以将要动态查询的数据存储为“类型化”键值对的数组,如下所示:

 query_data: [
    { type: "company", value: "foo" },
    { type: "plan", value: "pro" },
    ... 
  ]

然后索引.type和.value

鉴于你的例子,这将是这样的:

> db.xx.findOne()
{
    "_id" : ObjectId("515ca2bc57a0887a97cc8d14"),
    "name" : "Thiago",
    "id" : 2093,
    "country" : "Portugal",
    "custom_data" : [
        {
            "type" : "company",
            "value" : "foo"
        },
        {
            "type" : "plan",
            "value" : "pro"
        },
        {
            "type" : "department",
            "value" : "it"
        },
        {
            "type" : "sessions",
            "value" : 203
        }
    ]
}
> db.xx.ensureIndex({country:1,"custom_data.type":1,"custom_data.value":1})
> db.xx.find({country:"Portugal","custom_data.type":"sessions","custom_data.value":{$gt:100}}).explain()
{
    "cursor" : "BtreeCursor country_1_custom_data.type_1_custom_data.value_1",
    "isMultiKey" : true,
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 1,
    "nscannedAllPlans" : 1,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
        "country" : [
            [
                "Portugal",
                "Portugal"
            ]
        ],
        "custom_data.type" : [
            [
                "sessions",
                "sessions"
            ]
        ],
        "custom_data.value" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ]
    },
    "server" : "Aspire-5750:27017"
}
相关问题