Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use existing field as _id using elasticsearch dsl python DocType

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 ?

like image 441
Nilesh Avatar asked Jul 22 '16 19:07

Nilesh


1 Answers

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.

like image 158
Val Avatar answered Nov 14 '22 17:11

Val