【问题标题】:Persisted data with Django and Algolia search model indexing使用 Django 和 Algolia 搜索模型索引的持久数据
【发布时间】:2018-01-03 22:36:55
【问题描述】:

对于 Django+Algolia 来说,这是一个奇怪的问题。我正在使用 Algolia 特定的 Django 包:

$ pip install algoliasearch-django

我有以下模型架构:

import os
import datetime

from channels import Group

from django.db import models
from django.conf import settings
from django.utils.six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.core.files.storage import FileSystemStorage
from django.contrib.humanize.templatetags.humanize import naturaltime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SITE_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/site'))
USER_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/user'))

@python_2_unicode_compatible
class Room(models.Model):
    """
    This model class sets up the room that people can chat within - much like a forum topic.
    """
    title = models.CharField(max_length=255)
    staff = models.BooleanField(default=False)
    slug = models.SlugField(max_length=250, default='')
    banner = models.ImageField(storage=USER_UPLOAD_LOC, null=True, blank=True)

    def last_activity(self):
        """
        For date and time values show how many seconds, minutes, or hours ago a message
        was sent (i.e., persised to the database) compared to current timestamp return representing string.
        """
        last_persisted_message = Messages.objects.filter(where=self.slug).order_by('-sent_at').first()
        if last_persisted_message is not None:
            # First we can store "last persisted message" time in ISO format (could be useful for sitemap.xml generation; SEO tasks etc)
            last_persisted_message_iso = last_persisted_message.sent_at.isoformat()
            # Use the natural time package form contrib.humanize to convert our datetime to a string.
            last_persisted_message = naturaltime(last_persisted_message.sent_at)
            return last_persisted_message
        else:
            return "No activity to report"

索引为:

from algoliasearch_django import AlgoliaIndex

class RoomIndex(AlgoliaIndex):
    fields = ('title', 'last_activity')

    settings = {
        'searchableAttributes': ['title'],
        'attributesForFaceting': ['title', 'last_activity'],
        'hitsPerPage': 15,
    }

    index_name = 'Room Index'

本质上,要将“last_activity”值带到前端,它需要通过索引,据我所知,该索引已更新:

$ python manage.py algolia_reindex

但是,最后一个活动来自上一次(转换为人性化的 django naturaltime,例如“3 天前”等)在 websocket 连接中发送消息 - 持久化到数据库。除了更新我需要运行 algolia_reindex 命令之外,所有这些功能都有效。

不太确定如何同时进行更多操作...?

【问题讨论】:

    标签: python django algolia django-1.11


    【解决方案1】:

    好的,所以这个稍微复杂一些,因为我使用的是 websockets。当消息被发送并持久化到数据库时,我们还可以在相关的“消费者”方法中执行以下操作(实际上,consumers.py 是 views.py 文件的 websocket 等价物,所以我应该知道这一点!)

    以下代码行有效:

    client = algoliasearch.Client(settings.ALGOLIA['APPLICATION_ID'], settings.ALGOLIA['API_KEY'])
    index = client.init_index('Room Index')
    res = index.partial_update_objects([{"last_activity": naturaltime(datetime.datetime.now()), "objectID": your_object_id]}])
    

    任何监听的技巧都是根据从客户端传递给消费者的消息值来指定 your_object_id。

    别忘了补充:

    import datetime
    from django.conf import settings
    from django.contrib.humanize.templatetags.humanize import naturaltime
    

    在 consumer.py 文件的顶部!

    我还发现来自 Algolia 的特定于 python 的增量更新文档非常有用: 我https://www.algolia.com/doc/tutorials/indexing/synchronization/incremental-updates/

    要“实时”渲染更新的时间 - 使用哪个前端工具让你的船漂浮,我使用了 jQuery,但 Vue.js 或 React.js 也同样适用。

    【讨论】:

    猜你喜欢
    • 2014-10-23
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多