Google App Engine - Using Search API Python with list fields

让人想犯罪 __ 提交于 2019-12-04 21:33:49

问题


I'm using ndb.Model. The Search API has the following field classes:

    TextField : plain text
    HtmlField : HTML formatted text
    AtomField : a string which is treated as a single token
    NumberField : a numeric value (either float or integer)
    DateField : a date with no time component
    GeoField : a locale based on latitude and longitude

Suppose I have a 'tags' field which is a list field:

    tags = ndb.StringProperty(repeated=True)

How am I supposed to treat this field with search.Document?

Right now I'm turning tags list into a string:

    t = '|'.join(tags)

And then:

    search.TextField(name=cls.TAGS, value=t)

Any suggestions?


回答1:


Use unique identifiers for each "tag". Then you can create a document like:

doc = search.Document(fields=[
    search.TextField(name='tags', value='tag1 tag2 tag3'),
])
search.Index(name='tags').put(doc)

You can even use numbers (ids) as strings:

doc = search.Document(fields=[
    search.TextField(name='tags', value='123 456 789'),
])

And query using operators as you wish:

index = search.Index(name='tags')
results = index.search('tags:(("tag1" AND "tag2") OR ("tag3" AND "tag4"))')



回答2:


You should add as many fields as 'tags' you have, all with the same field_name:

doc = search.Document(fields=[
    search.TextField(name='tag', value=t) for t in tags
])

As in the docs:

A field can contain only one value, which must match the field's type. Field names do not have to be unique. A document can have multiple fields with the same name and same type, which is a way to represent a field with multiple values. (However, date and number fields with the same name can't be repeated.) A document can also contain multiple fields with the same name and different field types.



来源:https://stackoverflow.com/questions/16409006/google-app-engine-using-search-api-python-with-list-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!