【问题标题】:Remove object from haystack index从干草堆索引中删除对象
【发布时间】:2014-03-07 05:16:21
【问题描述】:

我使用 django 删除了一条记录:

 r = model.objects.get(id=1)
 r.delete()

现在我想从索引中删除记录而不重新索引。怎么样?

我无法让 remove_object 工作并且haystack docs 级别太高。我不能只运行“python manage.py update_index -- remove”,因为这也会重新索引所有内容。

【问题讨论】:

    标签: django indexing django-haystack


    【解决方案1】:

    哈,答案很简单,但也很老套。基本上,以下代码有效,因为如果您正确计时(最后一小时内数据库中没有条目),它只会删除已删除记录的索引条目。瞧。

      python manage.py update_index --remove --age=1
    

    【讨论】:

    【解决方案2】:

    有 2 个选项可以删除单个对象。

    • 第一种方法:

    您可以使用remove_object (Django Haystack Docs) 或update_object (Django Haystack Docs) 删除或更新单个对象是class SearchIndex 的方法

    您可以提供一个实例对象以及应该使用哪个连接。

    SearchIndex.remove_object(self, instance, using=None, **kwargs)

    从索引中删除一个对象。附加到类的删除后挂钩。

    SearchIndex.update_object(self, instance, using=None, **kwargs)

    更新单个对象的索引。附加到类的保存后挂钩。

    如果提供了using,它指定应该使用哪个连接。 >默认依赖于路由器来决定应该使用哪个后端。

    例子:

    
    from myapp.search_indexes import MyIndex
    
    # Get the object you want to delete or update
    instance = YourModel.objects.get(id=id)
    
    # settings.HAYSTACK_CONNECTIONS / name of your index
    using = "myindex_name"
    
    # Remove object
    MyIndex().remove_object(instance, using)
    
    # Update object
    MyIndex().update_object(instance, using)
    
    • 第二种方法:

    您可以通过SearchBackend.remove()删除单个对象

    这里有一些例子:

    
    from haystack import connections as haystack_connections
    
    # Get the object you want to delete or update
    instance = YourModel.objects.get(id=id)
    
    # Get all Names/keys of your indexes / settings.HAYSTACK_CONNECTIONS
    backend_names = haystack_connections.connections_info.keys()
    
    # Get key of connection for your object
    using = backend_names[0]
    
    # Get the backend 
    backend = haystack_connections[using].get_backend()
    
    # To remove object
    backend.remove(instance)
    

    【讨论】:

      【解决方案3】:

      实际上一个更简单的解决方案是使用 SignalProcessor (docs),连接到 post_delete 将在您从 orm 中删除文档时自动删除它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-02
        • 1970-01-01
        • 1970-01-01
        • 2012-05-22
        • 1970-01-01
        • 1970-01-01
        • 2012-03-19
        相关资源
        最近更新 更多