JCJ*_*CJS 8 nested nosql elasticsearch pyes
我是Elastic Search和非SQL范例的新手.我一直在关注ES教程,但有一件事我无法工作.
在下面的代码中(我使用PyES与ES交互)我创建了一个带有嵌套字段(主题)的单个文档,其中包含另一个嵌套字段(概念).
from pyes import *
conn = ES('127.0.0.1:9200') # Use HTTP
# Delete and Create a new index.
conn.indices.delete_index("documents-index")
conn.create_index("documents-index")
# Create a single document.
document = {
"docid": 123456789,
"title": "This is the doc title.",
"description": "This is the doc description.",
"datepublished": 2005,
"author": ["Joe", "John", "Charles"],
"subjects": [{
"subjectname": 'subject1',
"subjectid": [210, 311, 1012, 784, 568],
"subjectkey": 2,
"concepts": [
{"name": "concept1", "score": 75},
{"name": "concept2", "score": 55}
]
},
{
"subjectname": 'subject2',
"subjectid": [111, 300, 141, 457, 748],
"subjectkey": 0,
"concepts": [
{"name": "concept3", "score": 88},
{"name": "concept4", "score": 55},
{"name": "concept5", "score": 66}
]
}],
}
# Define the nested elements.
mapping1 = {
'subjects': {
'type': 'nested'
}
}
mapping2 = {
'concepts': {
'type': 'nested'
}
}
conn.put_mapping("document", {'properties': mapping1}, ["documents-index"])
conn.put_mapping("subjects", {'properties': mapping2}, ["documents-index"])
# Insert document in 'documents-index' index.
conn.index(document, "documents-index", "document", 1)
# Refresh connection to make queries.
conn.refresh()
Run Code Online (Sandbox Code Playgroud)
我能够查询主题嵌套字段:
query1 = {
"nested": {
"path": "subjects",
"score_mode": "avg",
"query": {
"bool": {
"must": [
{
"text": {"subjects.subjectname": "subject1"}
},
{
"range": {"subjects.subjectkey": {"gt": 1}}
}
]
}
}
}
}
results = conn.search(query=query1)
for r in results:
print r # as expected, it returns the entire document.
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何基于概念嵌套字段进行查询.
ES 文档指的是
自动支持并检测多级嵌套,从而导致内部嵌套查询自动匹配相关嵌套级别(而不是根),如果它存在于另一个嵌套查询中.
所以,我尝试使用以下格式构建查询:
query2 = {
"nested": {
"path": "concepts",
"score_mode": "avg",
"query": {
"bool": {
"must": [
{
"text": {"concepts.name": "concept1"}
},
{
"range": {"concepts.score": {"gt": 0}}
}
]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
返回0结果.
我无法弄清楚缺少什么,我没有找到任何基于两个嵌套级别的查询示例.
JCJ*_*CJS 12
好吧,在尝试组合音后,我终于使用以下查询得到它:
query3 = {
"nested": {
"path": "subjects",
"score_mode": "avg",
"query": {
"bool": {
"must": [
{
"text": {"subjects.concepts.name": "concept1"}
}
]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,无论嵌套属性级别如何,嵌套路径属性(主题)始终相同,并且在查询定义中,我使用了属性的完整路径(subject.concepts.name).
| 归档时间: |
|
| 查看次数: |
8543 次 |
| 最近记录: |