How to make union query on Elasticsearch?

随声附和 提交于 2019-12-22 07:59:58

问题


I would like to make a query with UNION and limit.

I can explain that query on mysql.

(SELECT 
    *
FROM table
WHERE type='text'
LIMIT 3
)
UNION
(SELECT 
    *
FROM table
WHERE type='word'
LIMIT 3
)

I tried it on Elasticsearch

{

    "query":{
        "dis_max":{
            "queries":[
                {
                    "from":0,
                    "size":3,
                    "query":{
                        "match":{
                            "type":"text"
                        }
                    }
                },
                {
                    "from":0,
                    "size":3,
                    "query":{
                        "match":{
                            "type":"word"
                        }
                    }
                }
            ]
        }
    }

}

http://localhost:9200/test/table/_search?pretty&source={%22query%22:{%22dis_max%22:{%22queries%22:[{%22query%22:{%22match%22:{%22type%22:%22test%22}}}]}}} Then, the error occured.

{
  "error" : {
    "root_cause" : [ {
      "type" : "query_parsing_exception",
      "reason" : "[_na] query malformed, no field after start_object",
      "index" : "test",
      "line" : 1,
      "col" : 34
    } ],
    "type" : "search_phase_execution_exception",
    "reason" : "all shards failed",
    "phase" : "query",
    "grouped" : true,
    "failed_shards" : [ {
      "shard" : 0,
      "index" : "test",
      "node" : "U6yIqY-pS526Vz8QTi6d0Q",
      "reason" : {
        "type" : "query_parsing_exception",
        "reason" : "[_na] query malformed, no field after start_object",
        "index" : "test",
        "line" : 1,
        "col" : 34
      }
    } ]
  },
  "status" : 400
}

When I use only match query, it worked. But with size, it doesn't work.

How can I solve it?


回答1:


The way to go is MultiSearch

curl -XGET 'http://127.0.0.1:9200/indexname/_msearch'  -d '
{}
{"query" : {"term" : {"type" : "text"}}, "size" : 3}
{}
{"query" : {"term" : {"type" : "word"}}, "size" : 3}
'


来源:https://stackoverflow.com/questions/41603882/how-to-make-union-query-on-elasticsearch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!