Skip to main content
 首页 » 编程设计

python之在 Django/ElasticSearch 中使用 HstoreField

2025年01月19日39Free-Thinker

我是 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