python - 在 Django/ElasticSearch 中使用 HstoreField

标签 python django python-3.x elasticsearch elasticsearch-py

我是 Elasticsearch 的新手,我真的很想在我的 Django 项目中实现它。
我的问题:我想存储一个 Python dict 对象

 ({'key_1': 'value_1', 'key_2': 'value_2', [...]})  

并确保我的搜索会查找每个键。
在 Django 中,我使用 Hstore 字段,我可以访问我的数据

Model.objects.get(hstorefield__key='value')

有没有人有想法使用 Elasticsearch 来做到这一点,并确保跟踪我的 Hstorefield 的所有 key ?

感谢您的帮助!

这是我的 Django 模型:

class Product(models.Model):

    code = models.BigIntegerField()
    url_off = models.URLField()
    creator = models.CharField(max_length=200)
    product_name = models.CharField(max_length=200)
    last_modified_t = models.DateTimeField()
    created_t = models.DateTimeField()
    metadatas = HStoreField()

最佳答案

默认情况下,您在文档中索引到 elasticsearch 的所有字段都将被索引并可用于搜索和过滤。您所要做的就是生成一个文档,其中还包含您 HStoreField 中的字段。如果您想控制这些字段的映射,您需要先定义它们,例如使用 DocType (0) 类(类似于 django 的 Model):

from elasticsearch_dsl import DocType, Long, Text, Keyword,Date, Object, InnerDoc

class Metadata(InnerDoc):
    meta_field = Text()
    meta_number = Long()
    ...

class Product(DocType):
    code = Long()
    creator = Text(fields={'keyword': Keyword()})
    last_modified_t = Date()
    metadata = Object(Metadata)
    class Meta:
        index = 'i'

# create the index in elasticsearch, only run once
Product.init()

然后您只需要在您的模型上创建一个方法,将其序列化到 Product 类中:

def to_search(self):
    return Product(
      _id=self.pk,
      code=self.code,
      creator=self.creator,
      metadata=Metadata(**self.metadatas)
    )

希望这对您有所帮助!

0 - http://elasticsearch-dsl.readthedocs.io/en/latest/persistence.html#doctype

关于python - 在 Django/ElasticSearch 中使用 HstoreField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954698/

相关文章:

python - 使用 python 登录网站并进行网页抓取

python - 如何对给定后缀的文件执行不区分大小写的搜索?

python - Seaborn 带状图,点前面有 fiddle 图条

Django-allauth:设置社交帐户后获取本地帐户

Django 缓存 - 如何设置我的代码以避免重复缓存逻辑?

python - 有没有办法确认 numpy 中的所有输入数组维度?

python - 如何在 Django API 中一次更新多条记录(批量更新)

python - 导入错误 : cannot import name '_safe_split'

python - 面临从建议下拉列表中选择第二项的问题

python-3.x - 训练多个 Keras NN 模型时出现段错误(核心转储)