7

I have class, where I try to set student_id as _id field in . 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 ?

Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • Can you show also how you create a new instance of a `StudentDoc``? – Val Jul 28 '16 at 19:35
  • @Val updated my question with more information. – Nilesh Jul 28 '16 at 19:41
  • @Val, there is [`MetaField`](https://github.com/elastic/elasticsearch-dsl-py/blob/master/elasticsearch_dsl/document.py#L27), but I don't know that will be useful here. – Nilesh Jul 28 '16 at 19:50

1 Answers1

8

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.

Val
  • 207,596
  • 13
  • 358
  • 360