Elasticsearch OR query

2019-07-22 05:28发布

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

    } 
  }
}

3条回答
家丑人穷心不美
2楼-- · 2019-07-22 05:55

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
      }
    }
  }
查看更多
Bombasti
3楼-- · 2019-07-22 06:07

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"
                    }
                }
            }
        }
    }
}
查看更多
做自己的国王
4楼-- · 2019-07-22 06:09

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"
        }
    }
}'
查看更多
登录 后发表回答