26

我正在做一些数据处理,如果我可以将一堆字典放在内存数据库中,然后对它运行简单的查询,这将变得相当简单。

例如,类似:

people = db([
    {"name": "Joe", "age": 16},
    {"name": "Jane", "favourite_color": "red"},
])
over_16 = db.filter(age__gt=16)
with_favorite_colors = db.filter(favorite_color__exists=True)

但是,有三个混杂因素:

  • 一些值将是 Python 对象,序列化它们是不可能的(太慢,破坏身份)。当然,我可以解决这个问题(例如,通过将所有项目存储在一个大列表中,然后在该列表中序列化它们的索引......但这可能需要相当多的摆弄)。
  • 将有成千上万的数据,我将对它们运行查找繁重的操作(如图形遍历),因此必须可以执行高效(即索引)查询。
  • 如示例中所示,数据是非结构化的,因此需要我预定义模式的系统会很棘手。

那么,这样的事情存在吗?还是我需要把一些东西拼凑在一起?

4

9 回答 9

10

如何通过sqlite3 标准库模块使用内存中的 SQLite 数据库,使用连接的特殊值:memory:?如果您不想编写 on SQL 语句,您始终可以使用 ORM,如SQLAlchemy来访问内存中的 SQLite 数据库。

编辑:我注意到您说这些值可能是 Python 对象,并且您需要避免序列化。要求将任意 Python 对象存储在数据库中也需要序列化。

如果您必须保留这两个要求,我可以提出一个实际的解决方案吗?为什么不直接使用 Python 字典作为 Python 字典集合的索引?听起来您对构建每个索引都有特殊的需求;找出你要查询的值,然后编写一个函数来为每个值生成和索引。字典列表中一个键的可能值将是索引的键;索引的值将是一个字典列表。通过将您要查找的值作为键来查询索引。

import collections
import itertools

def make_indices(dicts):
    color_index = collections.defaultdict(list)
    age_index = collections.defaultdict(list)
    for d in dicts:
        if 'favorite_color' in d:
            color_index[d['favorite_color']].append(d)
        if 'age' in d:
            age_index[d['age']].append(d)
    return color_index, age_index


def make_data_dicts():
    ...


data_dicts = make_data_dicts()
color_index, age_index = make_indices(data_dicts)
# Query for those with a favorite color is simply values
with_color_dicts = list(
        itertools.chain.from_iterable(color_index.values()))
# Query for people over 16
over_16 = list(
        itertools.chain.from_iterable(
            v for k, v in age_index.items() if age > 16)
)
于 2011-03-01T22:31:50.600 回答
5

我知道的唯一解决方案是几年前我在 PyPI 上偶然发现的一个包PyDbLite。没关系,但有几个问题:

  1. 它仍然希望将所有内容序列化到磁盘,作为一个泡菜文件。但这对我来说很简单。(这也是不必要的。如果插入的对象是可序列化的,那么整个集合也是可序列化的。)
  2. 基本记录类型是一个字典,它在其中插入自己的元数据,键__id__和下的两个整数__version__
  3. 索引非常简单,仅基于记录字典的值。如果您想要更复杂的东西,例如基于记录中对象的属性,您必须自己编写代码。(我本来打算自己做的事情,但一直没来得及做。)

作者似乎确实偶尔在研究它。我使用它时有一些新功能,包括一些用于复杂查询的好语法。

假设您撕掉了酸洗(我可以告诉您我做了什么),您的示例将是(未经测试的代码):

from PyDbLite import Base

db = Base()
db.create("name", "age", "favourite_color")

# You can insert records as either named parameters
# or in the order of the fields
db.insert(name="Joe", age=16, favourite_color=None)
db.insert("Jane", None, "red")

# These should return an object you can iterate over
# to get the matching records.  These are unindexed queries.
#
# The first might throw because of the None in the second record
over_16 = db("age") > 16
with_favourite_colors = db("favourite_color") != None

# Or you can make an index for faster queries
db.create_index("favourite_color")
with_favourite_color_red = db._favourite_color["red"]

希望这足以让您入门。

于 2011-03-01T23:53:49.917 回答
5

如果内存数据库解决方案最终工作量太大,这里有一种自己过滤它的方法,您可能会发现它很有用。

get_filter函数接受参数来定义您希望如何过滤字典,并返回一个可以传递给内置filter函数以过滤字典列表的函数。

import operator

def get_filter(key, op=None, comp=None, inverse=False):
    # This will invert the boolean returned by the function 'op' if 'inverse == True'
    result = lambda x: not x if inverse else x
    if op is None:
        # Without any function, just see if the key is in the dictionary
        return lambda d: result(key in d)

    if comp is None:
        # If 'comp' is None, assume the function takes one argument
        return lambda d: result(op(d[key])) if key in d else False

    # Use 'comp' as the second argument to the function provided
    return lambda d: result(op(d[key], comp)) if key in d else False

people = [{'age': 16, 'name': 'Joe'}, {'name': 'Jane', 'favourite_color': 'red'}]

print filter(get_filter("age", operator.gt, 15), people)
# [{'age': 16, 'name': 'Joe'}]
print filter(get_filter("name", operator.eq, "Jane"), people)
# [{'name': 'Jane', 'favourite_color': 'red'}]
print filter(get_filter("favourite_color", inverse=True), people)
# [{'age': 16, 'name': 'Joe'}]

这很容易扩展到更复杂的过滤,例如根据值是否与正则表达式匹配进行过滤:

p = re.compile("[aeiou]{2}") # matches two lowercase vowels in a row
print filter(get_filter("name", p.search), people)
# [{'age': 16, 'name': 'Joe'}]
于 2011-03-01T23:24:29.713 回答
3

就“身份”而言,任何可散列的东西都应该能够进行比较,以跟踪对象身份。

Zope 对象数据库 (ZODB): http ://www.zodb.org/

PyTables 运行良好: http ://www.pytables.org/moin

用于 Python 的 Metakit 也运行良好: http ://equi4.com/metakit/python.html
supports columns, and sub-columns but not unstructured data

研究“流处理”,如果您的数据集非常大,这可能很有用: http ://www.trinhhaianh.com/stream.py/

任何可以序列化(写入磁盘)的内存数据库都会出现身份问题。如果可能的话,我建议您将要存储的数据表示为本机类型(列表、字典)而不是对象。

请记住,NumPy 旨在对内存数据结构执行复杂的操作,如果您决定推出自己的解决方案,它可能会成为您解决方案的一部分。

于 2011-03-02T00:47:24.587 回答
3

我编写了一个名为Jsonstore的简单模块来解决 (2) 和 (3)。这是您的示例的方式:

from jsonstore import EntryManager
from jsonstore.operators import GreaterThan, Exists

db = EntryManager(':memory:')
db.create(name='Joe', age=16)
db.create({'name': 'Jane', 'favourite_color': 'red'})  # alternative syntax

db.search({'age': GreaterThan(16)})
db.search(favourite_color=Exists())  # again, 2 different syntaxes
于 2012-11-13T06:37:26.060 回答
1

不确定它是否符合您的所有要求,但 TinyDB(使用内存存储)也可能值得一试:

>>> from tinydb import TinyDB, Query
>>> from tinydb.storages import MemoryStorage
>>> db = TinyDB(storage=MemoryStorage)
>>> db.insert({'name': 'John', 'age': 22})
>>> User = Query()
>>> db.search(User.name == 'John')
[{'name': 'John', 'age': 22}]

它的简单性和强大的查询引擎使其成为某些用例的非常有趣的工具。有关详细信息,请参阅http://tinydb.readthedocs.io/ 。

于 2017-02-20T19:15:11.110 回答
0

如果您愿意解决序列化问题,MongoDB 可以为您工作。PyMongo 提供的界面几乎与您描述的相同。如果您决定序列化,则命中不会那么糟糕,因为 Mongodb 是内存映射的。

于 2011-03-01T22:32:14.667 回答
0

我昨天开始开发一个,它还没有发布。它索引您的对象并允许您运行快速查询。所有数据都保存在 RAM 中,我正在考虑智能加载和保存方法。出于测试目的,它通过 cPickle 加载和保存。

如果您仍然感兴趣,请告诉我。

于 2013-12-06T14:42:31.980 回答
0

应该可以用 isinstance()、hasattr()、getattr() 和 setattr() 来做你想做的事情。

但是,在您完成之前,事情会变得相当复杂!

我想可以将所有对象存储在一个大列表中,然后对每个对象运行查询,确定它是什么并查找给定的属性或值,然后将值和对象作为元组列表返回。然后你可以很容易地对你的返回值进行排序。copy.deepcopy 将是你最好的朋友,也是你最大的敌人。

听起来很有趣!祝你好运!

于 2011-03-01T22:59:19.390 回答