gpt4 book ai didi

python - 如何像 Freebase 一样存储数据?

转载 作者:太空狗 更新时间:2023-10-29 21:15:41 25 4
gpt4 key购买 nike

我承认这基本上是 Use freebase data on local server? 的重复问题但我需要比那里已经给出的更详细的答案

我已经完全爱上了 Freebase。我现在想要的是创建一个非常简单的 Freebase 克隆,用于存储可能不属于 Freebase 本身但可以使用 Freebase 模式描述的内容。本质上,我想要的是一种像 Freebase 本身那样存储数据的简单而优雅的方式,并且能够在 Python (CherryPy) Web 应用程序中轻松使用该数据。

MQL 引用指南的第 2 章指出:

The database that underlies Metaweb is fundamentally different than the relational databases that you may be familiar with. Relational databases store data in the form of tables, but the Metaweb database stores data as a graph of nodes and relationships between those nodes.



我猜这意味着我应该使用三元组或图形数据库(例如 Neo4j)?这里有人有使用 Python 环境中的其中一种的经验吗?

(到目前为止,我实际上尝试的是创建一个能够轻松存储 Freebase 主题的关系数据库模式,但我在配置 SQLAlchemy 中的映射时遇到了问题)。

我正在调查的事情
  • http://gen5.info/q/2009/02/25/putting-freebase-in-a-star-schema/
  • http://librdf.org/

  • 更新 [28/12/2011]:

    我在 Freebase 博客上找到了一篇文章,描述了 Freebase 自己使用的专有元组存储/数据库(图表): http://blog.freebase.com/2008/04/09/a-brief-tour-of-graphd/

    最佳答案

    这对我有用。它允许您在小于 100GB 的磁盘上的标准 MySQL 安装中加载所有 Freebase 转储。关键是了解转储中的数据布局,然后对其进行转换(针对空间和速度对其进行优化)。

    Freebase 概念 在尝试使用它之前,您应该了解(全部取自文档):

  • 主题 - '/common/topic' 类型的任何内容,注意您在 Freebase 中可能遇到的不同类型的 id - 'id'、'mid'、'guid'、'webid' 等
  • 域名
  • 类型 - “是一个”关系
  • 属性 - '具有'关系
  • 架构
  • 命名空间
  • key - '/en' 命名空间中的人类可读

  • 其他一些重要的 Freebase 细节 :
  • query editor是你的 friend
  • 理解描述的“来源”、“属性(property)”、“目的地”和“值(value)”概念here
  • 任何东西都有中音,甚至像“/”、“/m”、“/en”、“/lang”、“/m/0bnqs_5”等;使用查询编辑器进行测试:[{'id':'/','mid':null}]​
  • 您不知道数据转储中的任何实体(即行)是什么,您必须了解其类型才能做到这一点(例如,我怎么知道 '/m/0cwtm' 是人);
  • 每个实体至少有一种类型(但通常更多)
  • 每个实体至少有一个 id/key(但通常更多)
  • ontology (即元数据)嵌入在与数据相同的转储和相同的格式中(DBPedia 等其他发行版并非如此)
  • 转储中的“目的地”列是令人困惑的,它可能包含一个中间或一个键(参见下面的转换如何处理)
  • 域、类型、属性同时是命名空间级别(想出这个的人是天才恕我直言);
  • 了解什么是主题,什么不是主题(绝对重要),例如这个实体 '/m/03lmb2f'类型 '/film/performance'不是主题(我选择将这些视为 RDF 中的 Blank Nodes,尽管这在哲学上可能不准确),而 '/m/04y78wb'类型 '/film/director' (除其他外)是;

  • 变换

    (见底部的Python代码)

    转换 1 (来自 shell,从命名空间拆分链接,忽略 notable_for 和非/lang/en 文本):
    python parse.py freebase.tsv  #end up with freebase_links.tsv and freebase_ns.tsv

    变形2 (从 Python 控制台,在 freebase_ns_types.tsv、freebase_ns_props.tsv 上拆分 freebase_ns.tsv 加上我们现在忽略的其他 15 个)
    import e
    e.split_external_keys( 'freebase_ns.tsv' )

    变形3 (从 Python 控制台,将属性和目的地转换为 mids)
    import e
    ns = e.get_namespaced_data( 'freebase_ns_types.tsv' )
    e.replace_property_and_destination_with_mid( 'freebase_links.tsv', ns ) #produces freebase_links_pdmids.tsv
    e.replace_property_with_mid( 'freebase_ns_props.tsv', ns ) #produces freebase_ns_props_pmids.tsv

    变形4 (从 MySQL 控制台,在 DB 中加载 freebase_links_mids.tsv、freebase_ns_props_mids.tsv 和 freebase_ns_types.tsv):
    CREATE TABLE links(
    source VARCHAR(20),
    property VARCHAR(20),
    destination VARCHAR(20),
    value VARCHAR(1)
    ) ENGINE=MyISAM CHARACTER SET utf8;

    CREATE TABLE ns(
    source VARCHAR(20),
    property VARCHAR(20),
    destination VARCHAR(40),
    value VARCHAR(255)
    ) ENGINE=MyISAM CHARACTER SET utf8;

    CREATE TABLE types(
    source VARCHAR(20),
    property VARCHAR(40),
    destination VARCHAR(40),
    value VARCHAR(40)
    ) ENGINE=MyISAM CHARACTER SET utf8;

    LOAD DATA LOCAL INFILE "/data/freebase_links_pdmids.tsv" INTO TABLE links FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n';
    LOAD DATA LOCAL INFILE "/data/freebase_ns_props_pmids.tsv" INTO TABLE ns FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n';
    LOAD DATA LOCAL INFILE "/data/freebase_ns_base_plus_types.tsv" INTO TABLE types FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n';

    CREATE INDEX links_source ON links (source) USING BTREE;
    CREATE INDEX ns_source ON ns (source) USING BTREE;
    CREATE INDEX ns_value ON ns (value) USING BTREE;
    CREATE INDEX types_source ON types (source) USING BTREE;
    CREATE INDEX types_destination_value ON types (destination, value) USING BTREE;

    代码

    将其另存为 e.py:
    import sys

    #returns a dict to be used by mid(...), replace_property_and_destination_with_mid(...) bellow
    def get_namespaced_data( file_name ):
    f = open( file_name )
    result = {}

    for line in f:
    elements = line[:-1].split('\t')

    if len( elements ) < 4:
    print 'Skip...'
    continue

    result[(elements[2], elements[3])] = elements[0]

    return result

    #runs out of memory
    def load_links( file_name ):
    f = open( file_name )
    result = {}

    for line in f:
    if len( result ) % 1000000 == 0:
    print len(result)
    elements = line[:-1].split('\t')
    src, prop, dest = elements[0], elements[1], elements[2]
    if result.get( src, False ):
    if result[ src ].get( prop, False ):
    result[ src ][ prop ].append( dest )
    else:
    result[ src ][ prop ] = [dest]
    else:
    result[ src ] = dict([( prop, [dest] )])

    return result

    #same as load_links but for the namespaced data
    def load_ns( file_name ):
    f = open( file_name )
    result = {}

    for line in f:
    if len( result ) % 1000000 == 0:
    print len(result)
    elements = line[:-1].split('\t')
    src, prop, value = elements[0], elements[1], elements[3]
    if result.get( src, False ):
    if result[ src ].get( prop, False ):
    result[ src ][ prop ].append( value )
    else:
    result[ src ][ prop ] = [value]
    else:
    result[ src ] = dict([( prop, [value] )])

    return result

    def links_in_set( file_name ):
    f = open( file_name )
    result = set()

    for line in f:
    elements = line[:-1].split('\t')
    result.add( elements[0] )
    return result

    def mid( key, ns ):
    if key == '':
    return False
    elif key == '/':
    key = '/boot/root_namespace'
    parts = key.split('/')
    if len(parts) == 1: #cover the case of something which doesn't start with '/'
    print key
    return False
    if parts[1] == 'm': #already a mid
    return key
    namespace = '/'.join(parts[:-1])
    key = parts[-1]
    return ns.get( (namespace, key), False )

    def replace_property_and_destination_with_mid( file_name, ns ):
    fn = file_name.split('.')[0]
    f = open( file_name )
    f_out_mids = open(fn+'_pdmids'+'.tsv', 'w')

    def convert_to_mid_if_possible( value ):
    m = mid( value, ns )
    if m: return m
    else: return None

    counter = 0

    for line in f:
    elements = line[:-1].split('\t')
    md = convert_to_mid_if_possible(elements[1])
    dest = convert_to_mid_if_possible(elements[2])
    if md and dest:
    elements[1] = md
    elements[2] = dest
    f_out_mids.write( '\t'.join(elements)+'\n' )
    else:
    counter += 1

    print 'Skipped: ' + str( counter )

    def replace_property_with_mid( file_name, ns ):
    fn = file_name.split('.')[0]
    f = open( file_name )
    f_out_mids = open(fn+'_pmids'+'.tsv', 'w')

    def convert_to_mid_if_possible( value ):
    m = mid( value, ns )
    if m: return m
    else: return None

    for line in f:
    elements = line[:-1].split('\t')
    md = convert_to_mid_if_possible(elements[1])
    if md:
    elements[1]=md
    f_out_mids.write( '\t'.join(elements)+'\n' )
    else:
    #print 'Skipping ' + elements[1]
    pass

    #cPickle
    #ns=e.get_namespaced_data('freebase_2.tsv')
    #import cPickle
    #cPickle.dump( ns, open('ttt.dump','wb'), protocol=2 )
    #ns=cPickle.load( open('ttt.dump','rb') )

    #fn='/m/0'
    #n=fn.split('/')[2]
    #dir = n[:-1]


    def is_mid( value ):
    parts = value.split('/')
    if len(parts) == 1: #it doesn't start with '/'
    return False
    if parts[1] == 'm':
    return True
    return False

    def check_if_property_or_destination_are_mid( file_name ):
    f = open( file_name )

    for line in f:
    elements = line[:-1].split('\t')
    #if is_mid( elements[1] ) or is_mid( elements[2] ):
    if is_mid( elements[1] ):
    print line

    #
    def split_external_keys( file_name ):
    fn = file_name.split('.')[0]
    f = open( file_name )
    f_out_extkeys = open(fn+'_extkeys' + '.tsv', 'w')
    f_out_intkeys = open(fn+'_intkeys' + '.tsv', 'w')
    f_out_props = open(fn+'_props' + '.tsv', 'w')
    f_out_types = open(fn+'_types' + '.tsv', 'w')
    f_out_m = open(fn+'_m' + '.tsv', 'w')
    f_out_src = open(fn+'_src' + '.tsv', 'w')
    f_out_usr = open(fn+'_usr' + '.tsv', 'w')
    f_out_base = open(fn+'_base' + '.tsv', 'w')
    f_out_blg = open(fn+'_blg' + '.tsv', 'w')
    f_out_bus = open(fn+'_bus' + '.tsv', 'w')
    f_out_soft = open(fn+'_soft' + '.tsv', 'w')
    f_out_uri = open(fn+'_uri' + '.tsv', 'w')
    f_out_quot = open(fn+'_quot' + '.tsv', 'w')
    f_out_frb = open(fn+'_frb' + '.tsv', 'w')
    f_out_tag = open(fn+'_tag' + '.tsv', 'w')
    f_out_guid = open(fn+'_guid' + '.tsv', 'w')
    f_out_dtwrld = open(fn+'_dtwrld' + '.tsv', 'w')

    for line in f:
    elements = line[:-1].split('\t')
    parts_2 = elements[2].split('/')
    if len(parts_2) == 1: #the blank destination elements - '', plus the root domain ones
    if elements[1] == '/type/object/key':
    f_out_types.write( line )
    else:
    f_out_props.write( line )

    elif elements[2] == '/lang/en':
    f_out_props.write( line )

    elif (parts_2[1] == 'wikipedia' or parts_2[1] == 'authority') and len( parts_2 ) > 2:
    f_out_extkeys.write( line )

    elif parts_2[1] == 'm':
    f_out_m.write( line )

    elif parts_2[1] == 'en':
    f_out_intkeys.write( line )

    elif parts_2[1] == 'source' and len( parts_2 ) > 2:
    f_out_src.write( line )

    elif parts_2[1] == 'user':
    f_out_usr.write( line )

    elif parts_2[1] == 'base' and len( parts_2 ) > 2:
    if elements[1] == '/type/object/key':
    f_out_types.write( line )
    else:
    f_out_base.write( line )

    elif parts_2[1] == 'biology' and len( parts_2 ) > 2:
    f_out_blg.write( line )

    elif parts_2[1] == 'business' and len( parts_2 ) > 2:
    f_out_bus.write( line )

    elif parts_2[1] == 'soft' and len( parts_2 ) > 2:
    f_out_soft.write( line )

    elif parts_2[1] == 'uri':
    f_out_uri.write( line )

    elif parts_2[1] == 'quotationsbook' and len( parts_2 ) > 2:
    f_out_quot.write( line )

    elif parts_2[1] == 'freebase' and len( parts_2 ) > 2:
    f_out_frb.write( line )

    elif parts_2[1] == 'tag' and len( parts_2 ) > 2:
    f_out_tag.write( line )

    elif parts_2[1] == 'guid' and len( parts_2 ) > 2:
    f_out_guid.write( line )

    elif parts_2[1] == 'dataworld' and len( parts_2 ) > 2:
    f_out_dtwrld.write( line )

    else:
    f_out_types.write( line )

    将其另存为 parse.py:
    import sys

    def parse_freebase_quadruple_tsv_file( file_name ):
    fn = file_name.split('.')[0]
    f = open( file_name )
    f_out_links = open(fn+'_links'+'.tsv', 'w')
    f_out_ns = open(fn+'_ns' +'.tsv', 'w')

    for line in f:
    elements = line[:-1].split('\t')

    if len( elements ) < 4:
    print 'Skip...'
    continue

    #print 'Processing ' + str( elements )

    #cases described here http://wiki.freebase.com/wiki/Data_dumps
    if elements[1].endswith('/notable_for'): #ignore notable_for, it has JSON in it
    continue

    elif elements[2] and not elements[3]: #case 1, linked
    f_out_links.write( line )

    elif not (elements[2].startswith('/lang/') and elements[2] != '/lang/en'): #ignore languages other than English
    f_out_ns.write( line )

    if len(sys.argv[1:]) == 0:
    print 'Pass a list of .tsv filenames'

    for file_name in sys.argv[1:]:
    parse_freebase_quadruple_tsv_file( file_name )

    笔记:
  • 根据机器的不同,索引创建可能需要几个小时到 12 多个小时不等(但请考虑您正在处理的数据量)。
  • 为了能够双向遍历数据,您还需要在 links.destination 上建立索引,我发现它在时间上很昂贵并且从未完成。
  • 许多其他优化在这里是可能的。例如,'types' 表足够小,可以在 Python 字典中加载到内存中(参见 e.get_namespaced_data( 'freebase_ns_types.tsv' ))

  • 以及此处的标准免责声明。我这样做已经几个月了。我相信它大部分是正确的,但如果我的笔记遗漏了什么,我深表歉意。不幸的是,我需要它的项目失败了,但希望这对其他人有所帮助。如果有什么不清楚的,请在此处发表评论。

    关于python - 如何像 Freebase 一样存储数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8639888/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com