arraysfilterelasticsearchboolean-search

ElasticSearch bool search using array


I would like to be able to exclude a number of nodes in my ElasticSearch query. Currently this code is working perfectly, but it will only exclude two nodes ($nodeId1 and $nodeId2).

How would I change this query so I can use an array which would contain as many node IDs as I want? Thank you.

$data_string = '{
    "from" : 0, "size" : "' . $maximumResults . '",
    "query": {
        "filtered": {
            "query": {
                "match" : {
                    "thread.title" : {
                        "query" : "' . $threadTitle . '",
                        "operator": "or"
                    }
                }
            },
            "filter": {
                "bool" : {
                    "must" : [],
                    "must_not" : [
                        {
                            "term" : {"thread.discussion_id" : "' . $currentThreadId . '"}
                        }, 
                        { 
                            "term" : {"thread.node" : "' . $nodeId1 . '"}
                        },
                        { 
                            "term" : {"thread.node" : "' . $nodeId2 . '"}
                        }                                       
                    ],
                    "should" : []
                }
            }
        }
    }
}';

Solution

  • You can use the terms filter:

    $data_string = '{
        "from" : 0, "size" : "' . $maximumResults . '",
        "query": {
            "filtered": {
                "query": {
                    "match" : {
                        "thread.title" : {
                            "query" : "' . $threadTitle . '",
                            "operator": "or"
                        }
                    }
                },
                "filter": {
                    "bool" : {
                        "must" : [],
                        "must_not" : [
                            {
                                "term" : {"thread.discussion_id" : "' . $currentThreadId . '"}
                            }, 
                            { 
                                "terms" : {"thread.node" : ["' . $nodeId1 . '", "' . $nodeId2 . '", "' . $nodeId3 . '"}
                            }                                       
                        ],
                        "should" : []
                    }
                }
            }
        }
    }';