use existing field as _id using elasticsearch dsl python DocType

﹥>﹥吖頭↗ 提交于 2019-12-07 08:20:06

问题


I have class, where I try to set student_id as _id field in elasticsearch. I am referring persistent example from elasticsearch-dsl docs.

from elasticsearch_dsl import DocType, String

ELASTICSEARCH_INDEX = 'student_index'

class StudentDoc(DocType):
    '''
    Define mapping for Student type
    '''

    student_id = String(required=True)
    name = String(null_value='')

    class Meta:
        # id = student_id
        index = ELASTICSEARCH_INDEX

I tied by setting id in Meta but it not works.

I get solution as override save method and I achieve this

def save(self, **kwargs):
    '''
    Override to set metadata id
    '''
    self.meta.id = self.student_id
    return super(StudentDoc, self).save(**kwargs)

I am creating this object as

>>> a = StudentDoc(student_id=1, tags=['test'])
>>> a.save()

Is there any direct way to set from Meta without override save method ?


回答1:


There are a few ways to assign an id:

You can do it like this

a = StudentDoc(meta={'id':1}, student_id=1, tags=['test'])
a.save()

Like this:

a = StudentDoc(student_id=1, tags=['test'])
a.meta.id = 1
a.save()

Also note that before ES 1.5, one was able to specify a field to use as the document _id (in your case, it could have been student_id), but this has been deprecated in 1.5 and from then onwards you must explicitly provide an ID or let ES pick one for you.



来源:https://stackoverflow.com/questions/38533990/use-existing-field-as-id-using-elasticsearch-dsl-python-doctype

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