我想在我正在从事的项目上实现全局搜索功能,但是我在寻找如何构造正确查询方面遇到困难。现在,它始终不返回任何结果。这是我所拥有的:
models.py
class Product(models.Model):
name = models.CharField(max_length=200)
model_number = models.CharField(max_length=20, blank=True, null=True)
url = models.URLField(max_length=250, blank=True, null=True)
description = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
[... more non-relevant fields here...]
def __str__(self):
return self.name
class Meta:
db_table = 'products'
ordering = ['name']
documents.py
from django_elasticsearch_dsl import DocType, Index
from myapp import models as myapp_models
from users import models as user_models
products_index = Index('products')
products_index.settings(number_of_shards=1, number_of_replicas=0)
@products_index.doc_type
class ProductDocument(DocType):
class Meta:
model = myapp_models.Product
fields = ('id', 'name', 'model_number', 'description')
ignore_signals = True
[ .. other document definitions ... ]
views.py
client = Elasticsearch()
search_provider = Search(using=client)
class GlobalSearchView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, *args, **kwargs):
query = request.query_params.get('q', None)
# How to build the query here?
el_query = search_provider.query('term', query=query)
el_response = el_query.execute()
# Returning EL response for debugging purposes for now.
return Response(el_response.to_dict())
我想知道如何在视图中构建查询,因为尝试使用匹配查询和术语查询,响应中的hits数组始终为空。我希望用户搜索“再生书”之类的东西,Elasticsearch在所有索引(产品,品牌,公司,用户)和文档的所有字段中进行搜索,以查找包含查询中给出的任何单词的匹配项。我在文档中看到有一个名为“ Empty Search”的字词可以在各处搜索,但是我不确定如何在这里使用。
这是可行的,还是我总是需要指定需要搜索哪些索引和字段?您可以使用elasticsearch_dsl库将我引向此类查询的示例吗?
非常感谢!
以防万一,所有产品都已在ElasticSearch中建立了索引,因为如果我直接向EL _search
端点发出请求,则可以看到那里的所有文档。是Django的查询无法正常工作。
Version info:
Elasticsearch: elasticsearch-oss:6.2.4 (dockerized)
django-elasticsearch-dsl==0.5.0
elasticsearch==6.3.0
elasticsearch-dsl==6.1.0
Django==1.11.5