Django Haystack - 无法构建solr架构

时间:2017-09-23 10:14:07

标签: python django solr

当我尝试构建solr架构时出现以下错误:

const asyncFuncWithoutResult = (): Observable<void> => {
  // fake something async that has no return value

  const itWorked = true; // or not
  if (itWorked) {
    return Observable.of();
  } else {
    return Observable.throw(Error('It did not work'));
  }
}

// call the service
asyncFuncWithoutResult()
  .subscribe(
    undefined, // nothing will be emitted when using Observable.of()
    (err: any) => console.error(err), // handle error state
    () => console.log('Success'),     // handle success state
  );

也许这些信息会很有用:

mysite / settings.py 文件:

(my_env) pecan@tux ~/Documents/Django/mysite $ python manage.py build_solr_schema
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 29, in handle
    schema_xml = self.build_template(using=using)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 57, in build_template
    return t.render(c)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/backends/django.py", line 64, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
  File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/context.py", line 287, in make_context
    raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than Context.

博客/ search_indexes.py 文件:

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '****'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

SITE_ID = 1

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'blog',
    'taggit',
    'haystack',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/blog'
    },
}

blog / templates / search / indexes / blog / post_text.txt 文件:

from haystack import indexes
from .models import Post

class PostIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    publish = indexes.DateTimeField(model_attr='publish')

    def get_model(self):
        return Post

    def index_queryset(self, using=None):
        return self.get_model().published.all()

我使用Apache Solr 4.10.4,Python 3.4.5和Django 1.11.5。当我尝试在Python控制台中导入haystack时,我遇到了以下错误:

{{ object.title }}
{{ object.tags.all|join:", " }}
{{ object.body }}

我正在寻求帮助。

2 个答案:

答案 0 :(得分:1)

我的Django项目中的Haystack版本是错误的。我使用了django-haystack 2.6.1包,但是django模板上下文传递存在问题。此版本在上下文中传递了Context对象而不是字典。更多详情:https://github.com/django-haystack/django-haystack/pull/1504/commits/295584314e19a191a59450e053b21809adceca2a

django-haystack 2.6.1中的

haystack / management / commands / build_solr_schema.py

     content_field_name, fields = backend.build_schema(
         connections[using].get_unified_index().all_searchfields()
     )
     return Context({
         'content_field_name': content_field_name,
         'fields': fields,
         'default_operator': constants.DEFAULT_OPERATOR,
         'ID': constants.ID,
         'DJANGO_CT': constants.DJANGO_CT,
         'DJANGO_ID': constants.DJANGO_ID,
     })

 def build_template(self, using):
     t = loader.get_template('search_configuration/solr.xml')
django-haystack 2.7.dev0中的

haystack / management / commands / build_solr_schema.py

     content_field_name, fields = backend.build_schema(
         connections[using].get_unified_index().all_searchfields()
     )

     return {
         'content_field_name': content_field_name,
         'fields': fields,
         'default_operator': constants.DEFAULT_OPERATOR,
         'ID': constants.ID,
         'DJANGO_CT': constants.DJANGO_CT,
         'DJANGO_ID': constants.DJANGO_ID,
     }

 def build_template(self, using):
     t = loader.get_template('search_configuration/solr.xml')

我必须卸载django-haystack 2.6.1并使用命令安装更新的版本:

pip uninstall django-haystack
pip install django-haystack==2.7.dev0

我也解决了导入错误。在这种情况下,我只是将行HAYSTACK_ID_FIELD = 1添加到 settings.py 文件中,并将所需的环境变量DJANGO_SETTINGS_MODULE设置为值mysite.settings

我在编辑 settings.py 后执行了以下命令:

(my_env) pecan@tux ~/Documents/Django/mysite $ DJANGO_SETTINGS_MODULE="mysite.settings"
(my_env) pecan@tux ~/Documents/Django/mysite $ echo $DJANGO_SETTINGS_MODULE 
mysite.settings
(my_env) pecan@tux ~/Documents/Django/mysite $ DJANGO_SETTINGS_MODULE python
bash: DJANGO_SETTINGS_MODULE: command not found
(my_env) pecan@tux ~/Documents/Django/mysite $ python
Python 3.4.5 (default, Sep 17 2017, 18:19:56) 
[GCC 5.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import haystack
>>> 

现在django-haystack正常运作!

答案 1 :(得分:0)

调试干草堆

人们在第一次使用Haystack时遇到了一些常见问题。

“没有名为haystack的模块。”

首次将Haystack添加到项目中时,通常会出现此问题。

  • 您使用haystack中的django-haystack目录吗? 结帐/安装?

  • haystack上的PYTHONPATH目录?或者,是 符号链接到您的项目中的haystack

  • 启动Django shell(./manage.py shell)并尝试import haystack。您 可能会收到不同的,更具描述性的错误消息。

  • 仔细检查以确保您没有循环导入。 (即模块A. 尝试从试图从模块导入的模块B导入 甲。)

“未找到任何结果。”(在网页上)

有几个问题可能导致无法找到结果。最常见的是,要么没有运行rebuild_index来填充索引,要么只有一个空白的document=True字段,导致没有内容供引擎搜索。

  • 您是否在已安装的应用中找到了search_indexes.py

  • 您的数据库中是否有数据?

  • 您是否运行./manage.py rebuild_index索引所有内容 内容?

  • 尝试运行./manage.py rebuild_index -v2以获得更详细的输出 确保正在处理/插入数据。

  • 启动Django shell(./manage.py shell)并尝试:

  来自haystack.query的

导入SearchQuerySet

     

sqs = SearchQuerySet()。all()

     

sqs.count()

  • 你应该得到一个整数&gt; 0.如果没有,请检查以上和 重新索引。
  

sqs [0]#应该返回一个SearchResult对象。

     

sqs [0] .id#应该像'myapp.mymodel.1'那样回复。

     

sqs [0] .text#...或者您的文档= True field is。

  • 如果您返回u''None,则表示您的数据不是 使其成为被搜索的主要领域。你需要检查一下 该字段要么具有使用模型数据的模板,a model_attr直接从模型或a中提取数据 在索引时填充数据的prepare/prepare_FOO方法。
  • 检查搜索页面的模板,确保其循环播放 结果得当。还要确保它访问有效 从搜索引擎返回的字段或它正在尝试的字段 通过{{ result.object.foo }}查找访问相关模型。

来源:http://django-haystack.readthedocs.io/en/v2.4.1/toc.html