Microsoft Graph 查詢升級

微軟對Microsoft Graph的查詢功能進行了升級,現在可以很好地支持Azure AD對象的查詢了。

在以前,如果我們想要去查找用戶,可能會使用下面的URL

GET https://graph.microsoft.com/v1.0/users?$filter=startswith(displayName, 'justin')&$orderby=displayName&$select=id,displayName

但我們會收到如下的錯誤信息

"error": {
        "code": "Request_UnsupportedQuery",
        "message": "Sorting not supported for current query."
}

令人高興的是現我們能夠得到一個帶有@odata.count屬性的結果集了,當然查詢的請求需要做一些小的修改。

"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(id,displayName)",
"@odata.count": 2,
"value": [
   {
      "id": "4782e723-f4f4-4af3-a76e-25e3bab0d896",
      "displayName": "Justin Liu"
   },
   {
      "id": "c03e6eaa-b6ab-46d7-905b-73ec7ea1f755",
      "displayName": "Justin Li"
   }
]

要得到如上的返回內容,我們需要:

  1. 選擇beta版本的終結點
  2. 在URL查詢參數中增加$count=true
  3. 在請求headers中添加一個Key爲ConsistencyLevel,Value爲eventual的條目

Azure Active Directory存儲數據的多個副本,以處理大的讀量並提供高可用性。當數據更新時,更改將最終應用於所有副本。其中$search和$count查詢要求客戶端通過設置header的ConsistencyLevel爲eventual來選擇最終一致性。

下面列舉一些示例查詢

  • 租戶中有多少用戶?
GET https://graph.microsoft.com/beta/users/$count
  • 租戶中有多少訪客用戶?
GET https://graph.microsoft.com/beta/users/?$count=true&$filter=userType eq ‘Guest’
  • 某個組中有多少成員(包括可傳遞成員和直接的成員)?
GET https://graph.microsoft.com/beta/groups/{group-id}/transitiveMembers/$count

可傳遞是什麼意思呢?一個組可以包含嵌套組,那麼一個組中的組裏的成員,微軟使用transitiveMembers鏈接屬性去使組中組的成員爲父組的可傳遞成員。

標記化搜索目前只支持displayNamedescription屬性,它有一些搜索規則需要注意,搜索是基於這個規則,而不是完全的看是否包含要搜索的字符串。

  • 搜索顯示名中帶有“justin“的用戶
GET https://graph.microsoft.com/beta/users?$count=true&$search="displayName:justin"
  • 搜索顯示名中帶有”justin“或電子郵件以admin開頭的用戶,以顯示名排序
GET https://graph.microsoft.com/beta/users?$count=true&$search="displayName:justin" OR "mail:admin"&$orderBy=displayName
  • 搜索顯示名中帶有”team“的服務主體
GET https://graph.microsoft.com/beta/servicePrincipals?$count=true&$search="displayName:team"
  • 搜索一個組(包含子組)中顯示名中帶有”justin“的所有成員
GET https://graph.microsoft.com/beta/groups/{group-id}/transitiveMembers/microsoft.graph.user/?$count=true&$search="displayName:justin"

排序可以在篩選或查詢中使用,但目前僅限於displaynameuserPrincipalName屬性。

  • 獲取18號樓的用戶並以顯示名排序
GET https://graph.microsoft.com/beta/users?$count=true&$orderby=displayName&$filter=startswith(officeLocation, '18')

最後,別忘了批量執行Graph請求的操作,使用JSON批處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章