2016-11-20 141 views
1

上elasticsearch复杂的查询,我有一个书单,每本书有嵌套的标签:嵌套的对象

"hits": [ 
      { 
      "_index": "", 
      "_type": "", 
      "_id": "", 
      "_score": , 
      "_source": { 
       "name": "book1", 
       "tags": [ 
       { 
        "t": "tagA", 
        "w": 100 
       }, 
       { 
        "t": "tagB", 
        "w": 0 
       },     
       ], 

       "active": true, 
      } 
      }, 
      { 
      "_index": "", 
      "_type": "", 
      "_id": "", 
      "_score": , 
      "_source": { 
       "name": "book2", 
       "tags": [ 
       { 
        "t": "tagA", 
        "w": 100 
       }, 
       { 
        "t": "tagB", 
        "w": 0 
       },     
       ], 

       "active": true, 
      } 
      }, 
     { 
      "_index": "", 
      "_type": "", 
      "_id": "", 
      "_score": , 
      "_source": { 
       "name": "book3", 
       "tags": [ 
       { 
        "t": "tagC", 
        "w": 100 
       }, 
       { 
        "t": "tagB", 
        "w": 0 
       },     
       ], 

       "active": false, 
      } 
      }] 

首先,我试图让所有的“活跃”的书籍与特定的标签,这可以通过这个得到查询:

GET /index/type/_search 
{ 
    "query": { 
    "bool": { 
     "must_not": {"term" : { "active" : false}}, 
     "must": 
     [ 
     { 
     "nested": { 
      "path": "tags", 
      "query": { 
       "bool": { 
       "must": [ 
        { 
        "match": { 
         "tags.t": "tagB" 
        } 
        } 
       ] 
       } 
      } 
      } 
     } 
    ] 
    } 
    } 
} 

为上述,book1和book2返回。

但我现在想要得到的东西变得更加复杂。 我正在尝试使用特定标记(tagB)获得“有效”书籍。但是如果'tagC'在书中,那么如果书不活跃,书也可以返回。

所以对于这个问题,book1,book2,book3会返回。

如何在elasticsearch中执行此查询?

回答

1

试试这个,一个应该子句两个条件

{ 
    "query": { 
     "bool": { 

      "should": [ 
       { 
        "nested": { 
         "path": "tags", 
         "query": { 
          "bool": { 
           "must": [ 
            { 
             "match": { 
              "tags.t": "tagC" 
             } 
            } 
           ] 
          } 
         } 
        } 
       }, 
       { 
        "bool": { 
         "must": [ 
          { 
           "term": { 
            "active": true 
           } 
          }, 
          { 
           "nested": { 
            "path": "tags", 
            "query": { 
             "bool": { 
              "must": [ 
               { 
                "match": { 
                 "tags.t": "tagB" 
                } 
               } 
              ] 
             } 
            } 
           } 
          } 
         ] 
        } 
       } 
      ] 
     } 
    } 
}