如何在elasticsearch-dsl python中选择特定字段

时间:2015-11-19 07:55:26

标签: python elasticsearch elasticsearch-dsl

我使用elasticsearch dsl搜索elasticsearch:https://elasticsearch-dsl.readthedocs.org/en/latest/

如何在进行搜索查询时过滤特定字段:

我知道它在elasticsearch中受支持: https://www.elastic.co/guide/en/elasticsearch/reference/1.4/search-request-fields.html

我不知道如何在Elasticsearch-dsl

中做同样的事情

3 个答案:

答案 0 :(得分:6)

当您拥有Search对象时,可以在其上调用.fields()函数并指定要返回的字段:

s = search.Search()
s = s.fields(["field1", "field2"])
...

文档中未明确提及,但您可以在source for the search.py filetest cases for the fields function

中看到fields函数

更新

从ES 2.x开始,fields()方法已重命名为source()

答案 1 :(得分:2)

在elasticsearch-dsl版本6.x.x中fields()已弃用且结果异常。

使用source(fields=None, **kwargs)projection

e.g。

s = Search()
s = s.source(["field1", "field2"])
s = Search()
s = s.source(include=['obj1.*'], exclude=["*.description"])
s = Search()
s = s.source(include=['obj1.*']).source(exclude=["*.description"])

答案 2 :(得分:0)

我在所有领域使用它:

from elasticsearch_dsl import Q, Search
from elasticsearch import Elasticsearch 

client = Elasticsearch('localhost:9200')

q = Q("multi_match", query='STRING_TO_SEARCH', fields=['_all'])
result = Search(index='YOUR_INDEX').using(client).query(q).execute()

或特定字段:

fields=['name',]