Skip to content

search_index_service

django_spire.knowledge.entry.services.search_index_service

EntrySearchIndexService

Bases: BaseDjangoModelService['Entry']

Source code in django_spire/contrib/constructor/constructor.py
def __init__(self, obj: Any = None):
    self._obj_type_name: str = str(
        next(iter(self.__class__.__annotations__.values()))
    ).split('.')[-1]

    if obj is None:
        return

    self._obj_mro_type_names = [cls.__name__ for cls in obj.__class__.__mro__]

    if self._obj_type_name not in self._obj_mro_type_names:
        message = f'{self.__class__.__name__} was instantiated with obj type "{obj.__class__.__name__}" and failed as it was expecting "{self._obj_type_name}".'
        raise ConstructorError(message)

    self._obj_type: type[TypeAny] = obj.__class__

    if self._obj_type is None or self._obj_type is ...:
        message = f'{self.__class__.__name__} top class attribute must have an annotated type.'
        raise ConstructorError(message)

    self.obj: TypeAny = obj

    if ABC not in self.__class__.__bases__:
        if not self._obj_is_valid:
            message = f'{self._obj_type_name} failed to validate on {self.__class__.__name__}'
            raise ConstructorError(message)

    self.__post_init__()

obj instance-attribute

rebuild_search_index

Source code in django_spire/knowledge/entry/services/search_index_service.py
def rebuild_search_index(self):
    words = []

    words.append(self.obj.name)

    if self.obj.current_version is None:
        return

    for block in self.obj.current_version.blocks.active().order_by('order'):
        text = block.render_to_text().strip()

        if text and text != '\n':
            words.append(text)

    words.extend(
        tag.name
        for tag in self.obj.tags.all()
    )

    self.obj._search_text = '\n'.join(words)
    self.obj.save(update_fields=['_search_text'])

    if connection.vendor == 'postgresql':
        from django.contrib.postgres.search import SearchVector

        self.obj_class.objects.filter(pk=self.obj.pk).update(
            _search_vector=(
                SearchVector('name', weight='A', config='english') +
                SearchVector('_search_text', weight='B', config='english')
            )
        )

rebuild_all_search_indexes classmethod

Source code in django_spire/knowledge/entry/services/search_index_service.py
@classmethod
def rebuild_all_search_indexes(cls):
    from django_spire.knowledge.entry.models import Entry

    entries = (
        Entry.objects
        .active()
        .has_current_version()
        .select_related('current_version')
        .prefetch_related('current_version__blocks', 'tags')
    )

    for entry in entries.iterator(chunk_size=100):
        entry.services.search_index.rebuild_search_index()