ElasticSearch簡介(二)——簡單查詢

返回全部記錄 html

使用 GET 方法,直接請求/Index/_search,就會返回全部記錄。數據庫

GET /accounts/_search
{
    "took": 683,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "accounts",
                "_type": "person",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "user": "
張三",
                    "title": "
工程師",
                    "desc": "
數據庫管理,軟件開發"
                }
            }
        ]
    }
}
數組

上面代碼中,返回結果的 took字段表示該操做的耗時(單位爲毫秒),timed_out字段表示是否超時,hits字段表示命中的記錄,裏面子字段的含義以下。 elasticsearch

  • total:返回記錄數,本例是2條。
  • max_score:最高的匹配程度,本例是1.0。
  • hits:返回的記錄組成的數組。

返回的記錄中,每條記錄都有一個_score字段,表示匹配的程序,默認是按照這個字段降序排列。ide

  

全文搜索 ui

Elastic 的查詢很是特別,使用本身的查詢語法,要求 GET 請求帶有數據體。 spa

GET /accounts/_search
{
    "query": {
        "match": {
            "desc": "
軟件"
        }
    }
}
htm

上面代碼使用 Match 查詢,指定的匹配條件是desc字段裏面包含"軟件"這個詞。返回結果以下。 ip

{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.5753642,
        "hits": [
            {
                "_index": "accounts",
                "_type": "person",
                "_id": "1",
                "_score": 0.5753642,
                "_source": {
                    "user": "
張三
",
                    "title": "
工程師",
                    "desc": "
數據庫管理,軟件開發"
                }
            }
        ]
    }
}
開發

 

精確匹配

全面的match是模糊匹配的,若是咱們須要精確匹配,能夠使用match_phrase來實現。具體見後面的示例。

 

分頁

Elastic 默認一次返回10條結果,能夠經過size字段改變這個設置。

GET /person/_search
{
    "query": {
        "match": {
            "desc": "
管理
"
        }
    },
    "size": 1
}

上面代碼指定,每次只返回一條結果。

還能夠經過from字段,指定位移。

GET /accounts/_search
{
    "query": {
        "match": {
            "desc": "
管理
"
        }
    },
    "from": 1,
    "size": 1
}

上面代碼指定,從位置1開始(默認是從位置0開始),只返回一條結果。

  

邏輯運算

若是有多個搜索關鍵字, Elastic 認爲它們是or關係。

GET /accounts/_search
{
    "query": {
        "match": {
            "desc": "
軟件系統"
        }
    },
    "from": 0,
    "size": 1
}

上面代碼搜索的是軟件 or 系統。

若是要執行多個關鍵詞的and搜索,必須使用布爾查詢

GET /accounts/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "match_phrase": {
                        "user": "
張三"
                    }
                },
                {
                    "match": {
                        "desc": "
數據庫"
                    }                }            ]        }    }}

相關文章
相關標籤/搜索