嗨,我正在使用 haystack 和 woosh 作为搜索引擎:
我的模型如下
class Person(models.Model):
personid = models.IntegerField(primary_key = True, db_column = 'PID')
firstname = models.CharField(max_length = 50, db_column = 'FIRSTNAME')
lastname = models.CharField(max_length = 50, db_column = 'LASTNAME')
class Meta:
db_table = '"TEST"."PERSON"'
managed = False
class TDoc(models.Model):
tdocid = models.IntegerField(primary_key = True, db_column = 'TDOCID')
person = models.ForeignKey(Person, db_column = 'PID')
content = models.TextField(db_column = 'CONTENT', blank = True)
filepath = models.TextField(db_column = 'FILEPATH', blank = True)
class Meta:
db_table = '"TEST"."TDOC"'
managed = False
search_index.py如下:
class TDocIndex(SearchIndex):
content = CharField(model_attr = 'content', document = True)
filepaht = CharField(model_attr = 'filepath')
person = CharField(model_attr = 'person')
def get_queryset(self):
return TDoc.objects.all()
def prepare_person(self, obj):
# Store a list of id's for filtering
return obj.person.lastname
site.register(TDoc, TDocIndex)
我的问题是我想做多个归档搜索,例如
内容:xxx 和人物:SMITH
在干草堆上它会立即搜索所有内容,我无法进行特定的字段搜索。 我怀疑我的索引已损坏,但是:
ix = open_dir("/testindex")
searcher = ix.searcher()
mparser = MultifieldParser(["content", "filepath", "person"], schema = ix.schema)
myquery = mparser.parse(content:xxx AND person:SMITH')
results = searcher.search(myquery)
for result in results:
print result
但是它可以工作并且返回正确的值。 我正在使用教程中的标准 haystack SearchView,search.html
(r'^search/', include('haystack.urls')),
在索引中,您应该使用
document=True
定义一个字段,这是将搜索的文档 haystack。按照惯例,该字段被命名为 text
。如果您打算对字段的值进行过滤或排序,则可以添加额外的字段。
执行搜索时考虑多个字段的方法是将文档定义为模板,并在文档字段上设置
use_template
。您的索引将如下所示:
class TDocIndex(SearchIndex):
text = CharField(document=True, use_template=True)
#if you plan to filter by person
personid = IntegerField(model_attr='person__id')
site.register(TDoc, TDocIndex)
您将拥有一个 search/indexes/tdoc_text.txt 模板,例如:
{{ object.content }}
{{ object.filepath }}
{{ object.person.lastname }}
请参阅这个答案。
您可以在索引类中使用
prepare
方法,如下所示:
from apps.main.models import Person
from haystack import indexes
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True)
lastname = indexes.CharField(null=True)
date_insert = indexes.DateTimeField(model_attr="date_insert", indexed=False)
date_update = indexes.DateTimeField(model_attr="date_update", indexed=False)
def get_model(self):
return Person
def get_updated_field(self):
return "date_update"
def index_queryset(self, using="default"):
return self.get_model().objects.all()
def prepare(self, obj: Person):
data = super().prepare(obj)
main_fields = [obj.content, obj.filepath, obj.person.lastname]
data["text"] = "\n".join(f"{col}" for col in main_fields)
data["lastname"] = obj.person.lastname.lower()
return data