2016-11-20 5 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'が本にあれば、それがアクティブでなければ本も返ることができます。

この質問では、本1、本2、本3が返ってきます。

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" 
                } 
               } 
              ] 
             } 
            } 
           } 
          } 
         ] 
        } 
       } 
      ] 
     } 
    } 
}