Elasticsearch OR query

狂风中的少年 提交于 2019-12-11 04:09:04

问题


Can anyone tell me how do I write the below Mysql query in elastisearch

Select * from `table` WHERE `Name`='A' OR `Name`='B' order by `rank` DESC

I have tried multiple solutions the internet like

{

"sort":{"rank":{"order":"desc"}}, 

"query": {

    "query_string" : {
        "fields" : ["Name"],
        "query" : "A OR B"
    }


}

and also tried the below code

{

"sort":{"rank":{"order":"desc"}}, 

  "query" : {
    "bool": {
      "should": [
        {
          "match_phrase" : {
            "Name" : "A"
          }
        },
        {
          "match_phrase": {
            "Name": "B"
          }
        }
      ]

    } 
  }
}

回答1:


You could do it with Bool-Filter and Order on all Documents:

{
  "query": {
    "match_all": {}
  },
  "filter": {
    "bool": {
      "should": [
        {
          "term": {
            "Name": "A"
          }
        },{
          "term": {
            "Name": "B"
          }
        }
      ]
    }
  },"sort": [
    {
      "rank": {
        "order": "desc"
      }
    }
  ]
}

Or have a subset with Range Query:

"query": {
    "range": {
      "JoinDate": {
        "lte": 1431051540
      }
    }
  }



回答2:


This is my current mappings are

{
    "class": {
        "mappings": {
            "students": {
                "properties": {
                    "Name": {
                        "type": "string"
                    },
                    "rank": {
                        "type": "string"
                    },
                    "Description": {
                        "type": "string"
                    },
                    "Image": {
                        "type": "string"
                    },
                    "JoinDate": {
                        "type": "date",
                        "format": "dateOptionalTime"
                    }
                }
            }
        }
    }
}



回答3:


Try Terms filter. Below is equivalent of SQL query you wrote.

curl -XGET 'http://localhost:9200/_search?pretty' -d '{
    "filter": {
        "terms": {
            "Name": ["A", "B"]
        }
    },
    "sort": {
        "rank": {
            "order": "desc"
        }
    }
}'


来源:https://stackoverflow.com/questions/30099940/elasticsearch-or-query

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