Python elasticsearch_dsl.Document() Examples

The following are 8 code examples of elasticsearch_dsl.Document(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module elasticsearch_dsl , or try the search function .
Example #1
Source File: elasticsearch.py    From qb with MIT License 6 votes vote down vote up
def create_doctype(index_name, similarity):
    if similarity == 'default':
        wiki_content_field = Text()
        qb_content_field = Text()
    else:
        wiki_content_field = Text(similarity=similarity)
        qb_content_field = Text(similarity=similarity)

    class Answer(Document):
        page = Text(fields={'raw': Keyword()})
        wiki_content = wiki_content_field
        qb_content = qb_content_field

        class Meta:
            index = index_name

    return Answer 
Example #2
Source File: test_index.py    From elasticsearch-dsl-py with Apache License 2.0 6 votes vote down vote up
def test_multiple_doc_types_will_combine_mappings():
    class User(Document):
        username = Text()

    i = Index('i')
    i.document(Post)
    i.document(User)
    assert {
        'mappings': {
            'properties': {
                'title': {'type': 'text'},
                'username': {'type': 'text'},
                'published_from': {'type': 'date'}
            }
        }
    } == i.to_dict() 
Example #3
Source File: indices.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        """Perform initial checks and save given object."""
        class_name = type(self).__name__
        if not self.object_type:
            raise RuntimeError("`object_type` must be defined in {}".format(class_name))

        if not self.document_class:
            raise RuntimeError(
                "`document_class` must be defined in {}".format(class_name)
            )

        if self.queryset is None:
            raise RuntimeError("`queryset` must be defined in {}".format(class_name))

        # Apply any extensions defined for the given document class. Document class extensions
        # come in the form of field definitions.
        self.document_class = copy.deepcopy(self.document_class)
        for extension in composer.get_extensions(self.document_class):
            for name in dir(extension):
                field = getattr(extension, name)
                if isinstance(field, dsl.Field):
                    self.document_class._doc_type.mapping.field(name, field)

        #: list of built documents waiting to be pushed
        self.push_queue = []

        self._index_name = self.document_class()._get_index()
        self._mapping_created = False

        #: id of thread id where connection was established
        self.connection_thread_id = None 
Example #4
Source File: test_result.py    From elasticsearch-dsl-py with Apache License 2.0 5 votes vote down vote up
def test_bucket_keys_get_deserialized(aggs_data, aggs_search):
    class Commit(Document):
        info = Object(properties={'committed_date': Date()})

        class Index:
            name = 'test-commit'

    aggs_search = aggs_search.doc_type(Commit)
    agg_response = response.Response(aggs_search, aggs_data)

    per_month = agg_response.aggregations.per_month
    for b in per_month:
        assert isinstance(b.key, date) 
Example #5
Source File: test_validation.py    From elasticsearch-dsl-py with Apache License 2.0 5 votes vote down vote up
def test_required_int_can_be_0():
    class DT(Document):
        i = Integer(required=True)

    dt = DT(i=0)
    assert dt.full_clean() is None 
Example #6
Source File: test_validation.py    From elasticsearch-dsl-py with Apache License 2.0 5 votes vote down vote up
def test_required_field_cannot_be_empty_list():
    class DT(Document):
        i = Integer(required=True)

    dt = DT(i=[])
    with raises(ValidationException):
        dt.full_clean() 
Example #7
Source File: test_validation.py    From elasticsearch-dsl-py with Apache License 2.0 5 votes vote down vote up
def test_validation_works_for_lists_of_values():
    class DT(Document):
        i = Date(required=True)

    dt = DT(i=[datetime.now(), 'not date'])
    with raises(ValidationException):
        dt.full_clean()

    dt = DT(i=[datetime.now(), datetime.now()])
    assert None is dt.full_clean() 
Example #8
Source File: es_config.py    From georef-ar-api with MIT License 5 votes vote down vote up
def create_index(es, name, doc_class, shards, replicas, synonyms=None,
                 excluding_terms=None):
    """Crea un índice Elasticsearch utilizando un nombre y una clase de
    documento.

    Args:
        es (elasticsearch.Elasticsearch): Cliente Elasticsearch.
        name (str): Nombre del índice a crear.
        doc_class (type): Clase del documento (debe heredar de Document).
        shards (int): Cantidad de "shards" a utilizar para el índice.
        replicas (int): Cantidad de réplicas por "shard".
        synonyms (list): Lista de sinónimos a utilizar en caso de necesitar el
            analizador 'name_analyzer_synonyms'.
        excluding_terms (list): Lista de términos excluyentes a utilizar en
            caso de necesitar el analizador 'name_analyzer_excluding_terms'.

    """
    index = Index(name)

    # Crear el analizador 'name_analyzer_synonyms' solo si se lo pidió
    # explícitamente. Si el documento tipo 'doc_class' utiliza el analizador
    # en algún punto de su mapeo, la lista 'synonyms' debería estar presente.
    if synonyms is not None:
        index.analyzer(gen_name_analyzer_synonyms(synonyms))

    # Mismo razonamiento que con 'name_analyzer_synonyms'.
    if excluding_terms is not None:
        index.analyzer(gen_name_analyzer_excluding_terms(excluding_terms))

    index.document(doc_class)
    index.settings(number_of_shards=shards, number_of_replicas=replicas)
    index.create(using=es)