如何在我的GAE数据存储上实现搜索API?
我建立了一个数据库,想用GAE的搜索API来搜索它。我看过谷歌关于这个API的教程,但我最缺少的就是怎么把数据存储中的一种类型转换成一个“文档”。有没有好的教程可以参考一下?谢谢!
3 个回答
0
我有成千上万的实体(可以理解为数据或对象),我想为这些实体建立一个索引。然后我使用了一种叫做mapreduce的技术来构建这个索引,这样我就可以通过搜索API来搜索这些实体。这个mapreduce的工作过程是:
- name: buildindex
mapper:
input_reader: mapreduce.input_readers.DatastoreInputReader
handler: main.buildindex
params:
- name: entity_kind
default: main.Article
函数
def buildindex(entity):
try:
doc = search.Document(doc_id=str(entity.key()), fields=[
search.TextField(name='title', value=entity.title),
search.TextField(name='text', value=entity.text),
])
search.Index(name='myIndex').put(doc)
except Exception, e:
logging.exception('Mapreduce has exception:%s' % str(e))
0
很遗憾,这个是不可能的。
看一下Index构造函数(python),我们可以看到在早期阶段曾经尝试过实现这个功能,但实际上从来没有成功过。指定索引的来源已经被弃用了,现如今也不再有效。
这里是构造函数的文档:
class Index(object):
[...]
def __init__(self, name, namespace=None, source=SEARCH):
"""Initializer.
Args:
name: The name of the index. An index name must be a visible printable
ASCII string not starting with '!'. Whitespace characters are excluded.
namespace: The namespace of the index name. If not set, then the current
namespace is used.
source: Deprecated as of 1.7.6. The source of
the index:
SEARCH - The Index was created by adding documents throught this
search API.
DATASTORE - The Index was created as a side-effect of putting entities
into Datastore.
CLOUD_STORAGE - The Index was created as a side-effect of adding
objects into a Cloud Storage bucket.
[...]
"""
所以,至少目前(?),唯一的解决办法,就像Tim Hoffman提到的那样,就是将你的文档和索引与数据存储的数据分开处理。
你仍然可以向https://code.google.com/p/googleappengine/issues/list提交一个功能请求,看看会有什么进展。
3
你不能把 db.Model 或 ndb.Model 转换成 search.Document。
为什么呢?因为这样做没有太大意义。
我给你举个例子:假设你在 db.StringProperty() 中有一个字符串 'this-is-black-tag',你该怎么转换呢:
- 你可以把它当作原子(Atoms)来用,这样只有完全匹配的时候才算匹配。
- 你可以把它当作字符串(String)来用,这样它会被拆分成 'this'、'is'、'black'、'tag',然后再进一步拆分成 't'、'th'、'thi'、'this' 等等。
- 你也可以决定这个字符串不需要显示,因为它对搜索没有帮助,反而可能会误导搜索结果。
你需要自己设计搜索功能,这个功能应该是手动设计的,这就是答案。
你只需要:
- 创建 search.Document
- 添加字段
- 把文档添加到索引中
参考链接: https://developers.google.com/appengine/docs/python/search/documentclass