Funcionalidades avanzadas de consulta en objetos Microsoft Entra ID
Artículo
Microsoft Graph admite funcionalidades avanzadas de consulta en varios objetos de Microsoft Entra ID, también denominados objetos de directorio, para ayudarle a acceder de forma eficaz a los datos. Por ejemplo, la adición de los operadores No (not), No es igual (ne) y Termina con (endsWith) en el parámetro de consulta $filter.
El motor de consulta de Microsoft Graph usa un almacén de índices para satisfacer las solicitudes de consulta. Para agregar compatibilidad con funcionalidades de consulta adicionales en algunas propiedades, es posible que esas propiedades se indexen en un almacén independiente. Esta indexación independiente mejora el rendimiento de las consultas. Sin embargo, estas funcionalidades avanzadas de consulta no están disponibles de forma predeterminada, pero el solicitante debe establecer el encabezado eventualConsistencyLevel en y, excepto en $search, usar el parámetro de $count consulta. El encabezado ConsistencyLevel y $count se denominan parámetros de consulta avanzada.
Por ejemplo, si desea recuperar solo las cuentas de usuario inactivas, puede ejecutar cualquiera de estas consultas que usan el parámetro de consulta $filter.
Opción 1: Use el parámetro de $filter consulta con el eq operador . Esta solicitud funciona de forma predeterminada y no requiere los parámetros de consulta avanzados.
GET https://graph.microsoft.com/v1.0/users?$filter=accountEnabled eq false
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "accountEnabled eq false";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFilter := "accountEnabled eq false"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "accountEnabled eq false";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "accountEnabled eq false",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Opción 2: Use el parámetro de $filter consulta con el ne operador . Esta solicitud no se admite de forma predeterminada porque el ne operador solo se admite en consultas avanzadas. Por lo tanto, debe agregar el encabezado ConsistencyLevel establecido en eventualy usar la cadena de $count=true consulta.
GET https://graph.microsoft.com/v1.0/users?$filter=accountEnabled ne true&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "accountEnabled ne true";
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestFilter := "accountEnabled ne true"
requestCount := true
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Count: &requestCount,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "accountEnabled ne true";
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "accountEnabled ne true",
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Solo se admite usar $filter y $orderby juntos con consultas avanzadas.
$expand no se admite actualmente con consultas avanzadas.
Las funcionalidades de consulta avanzadas no están disponibles actualmente para los inquilinos de Azure AD B2C.
Para usar funcionalidades de consulta avanzadas en solicitudes por lotes, especifica el encabezado ConsistencyLevel en el cuerpo JSON de la solicitud de POST .
Compatibilidad con el filtrado por propiedades de objetos de Microsoft Entra ID (directorio)
Las propiedades de los objetos de directorio se comportan de forma diferente en cuanto a su compatibilidad con los parámetros de consulta. Los siguientes son escenarios comunes para los objetos del directorio:
El operador in se admite de forma predeterminada donde se admita el operador eq de forma predeterminada.
El endswith operador solo se admite con parámetros de consulta avanzados y solo por correo, otras propiedadesMails, userPrincipalName y proxyAddresses .
La obtención de colecciones vacías (/$count eq 0, /$count ne 0) y colecciones con menos de un objeto (/$count eq 1, /$count ne 1) solo se admite con parámetros de consulta avanzados.
Los not operadores de negación y ne solo se admiten con parámetros de consulta avanzados.
Todas las propiedades que admiten el eq operador también admiten los ne operadores o not .
En las tablas siguientes se resume la compatibilidad con $filter operadores por propiedades de objetos de directorio e indica dónde se admite la consulta a través de funcionalidades de consulta avanzadas.
Leyenda
El $filter operador funciona de forma predeterminada para esa propiedad.
El $filter operador solo funciona sin parámetros de consulta avanzados.
El $filter operador requiereparámetros de consulta avanzados, que son:
Encabezado ConsistencyLevel=eventual
Cadena de consulta $count=true
El $filter operador no se admite en esa propiedad.
Envíenos comentarios para solicitar que esta propiedad sea compatible con $filter para sus escenarios.
Las celdas en blanco indican que la consulta no es válida para esa propiedad.
La columna valor NULL indica que la propiedad admite valores NULL y se puede filtrar mediante null.
Las propiedades que no aparecen aquí no admiten $filter en absoluto.
Propiedades de unidad administrativa
Propiedad
eq
startsWith
eq Null
description
displayName
isMemberManagementRestricted
membershipRule
membershipRuleProcessingState
Propiedades de la aplicación
Propiedad
eq
startsWith
ge/le
eq Null
appId
createdDateTime
description
disabledByMicrosoftStatus
displayName
federatedIdentityCredentials/any(f:f/issuer)
federatedIdentityCredentials/any(f:f/name)
federatedIdentityCredentials/any(f:f/subject)
identifierUris/any(p:p)
info/logoUrl
info/termsOfServiceUrl
notas
publicClient/redirectUris/any(p:p)
publisherDomain
requiredResourceAccess/any(r:r/resourceAppId)
serviceManagementReference
signInAudience
spa/redirectUris/any(p:p)
tags/any(p:p)
uniqueName
verifiedPublisher/displayName
web/homePageUrl
web/redirectUris/any(p:p)
Las siguientes propiedades de la entidad de aplicación admiten $count una colección en una expresión de filtro.
Propiedad
eq Count 0
eq Count 1
extensionProperties/$count
federatedIdentityCredentials/$count
Propiedades del contrato
Propiedad
eq
startsWith
customerId
defaultDomainName
displayName
Propiedades de dispositivo
Propiedad
eq
startsWith
ge/le
eq Null
accountEnabled
alternativeSecurityIds/any(a:a/identityProvider)
alternativeSecurityIds/any(a:a/type)
approximateLastSignInDateTime
deviceCategory
deviceId
deviceOwnership
displayName
enrollmentProfileName
extensionAttributes/extensionAttribute1-15
hostnames/any(p:p)
isCompliant
isManaged
isRooted
managementType
manufacturer
mdmAppId
model
onPremisesLastSyncDateTime
onPremisesSecurityIdentifier
onPremisesSyncEnabled
operatingSystem
operatingSystemVersion
physicalIds/any(p:p)
profileType
registrationDateTime
trustType
Las siguientes propiedades de la compatibilidad de la entidad $count de dispositivo de una colección en una expresión de filtro.
Compatibilidad con la ordenación por propiedades de objetos de Microsoft Entra ID (directorio)
En la tabla siguiente se resume la compatibilidad con $orderby las propiedades de los objetos de directorio e indica dónde se admite la ordenación mediante funcionalidades de consulta avanzadas.
Leyenda
El $orderby operador funciona de forma predeterminada para esa propiedad.
El $orderby operador requiereparámetros de consulta avanzados, que son:
Control de errores para consultas avanzadas en objetos de directorio
En la sección siguiente se proporcionan ejemplos de escenarios de error comunes cuando no se usan parámetros de consulta avanzados cuando es necesario.
El recuento de objetos de directorio solo se admite mediante los parámetros de consultas avanzadas. Si no se especifica el ConsistencyLevel=eventual encabezado, la solicitud devuelve un error cuando se usa el $count segmento de dirección URL (/$count) o omite de forma silenciosa el $count parámetro de consulta (?$count=true) si se usa.
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
await graphClient.Users.Count.GetAsync();
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
//other-imports
)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
graphClient.Users().Count().Get(context.Background(), nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
graphClient.users().count().get();
<?php
use Microsoft\Graph\GraphServiceClient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$graphServiceClient->users()->count()->get()->wait();
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
await graph_client.users.count.get()
{
"error": {
"code": "Request_BadRequest",
"message": "$count is not currently supported.",
"innerError": {
"date": "2021-05-18T19:03:10",
"request-id": "d9bbd4d8-bb2d-44e6-99a1-71a9516da744",
"client-request-id": "539da3bd-942f-25db-636b-27f6f6e8eae4"
}
}
}
En el caso de los objetos de directorio, $search solo funciona en consultas avanzadas. Si no se especifica el encabezado ConsistencyLevel , la solicitud devuelve un error.
GET https://graph.microsoft.com/v1.0/applications?$search="displayName:Browser"
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Applications.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Search = "\"displayName:Browser\"";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphapplications "github.com/microsoftgraph/msgraph-sdk-go/applications"
//other-imports
)
requestSearch := "\"displayName:Browser\""
requestParameters := &graphapplications.ApplicationsRequestBuilderGetQueryParameters{
Search: &requestSearch,
}
configuration := &graphapplications.ApplicationsRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
applications, err := graphClient.Applications().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ApplicationCollectionResponse result = graphClient.applications().get(requestConfiguration -> {
requestConfiguration.queryParameters.search = "\"displayName:Browser\"";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.applications.applications_request_builder import ApplicationsRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = ApplicationsRequestBuilder.ApplicationsRequestBuilderGetQueryParameters(
search = "\"displayName:Browser\"",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.applications.get(request_configuration = request_configuration)
{
"error": {
"code": "Request_UnsupportedQuery",
"message": "Request with $search query parameter only works through MSGraph with a special request header: 'ConsistencyLevel: eventual'",
"innerError": {
"date": "2021-05-27T14:26:47",
"request-id": "9b600954-ba11-4899-8ce9-6abad341f299",
"client-request-id": "7964ef27-13a3-6ca4-ed7b-73c271110867"
}
}
}
Si una propiedad o un parámetro de consulta en la URL solo se admite en las consultas avanzadas pero falta el encabezado ConsistencyLevel o la cadena de consulta $count=true, la solicitud devuelve un error.
GET https://graph.microsoft.com/beta/users?$filter=endsWith(userPrincipalName,'%23EXT%23@contoso.com')
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "endsWith(userPrincipalName,'";
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestFilter := "endsWith(userPrincipalName,'"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "endsWith(userPrincipalName,'";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "endsWith(userPrincipalName,'",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
{
"error": {
"code": "Request_UnsupportedQuery",
"message": "Operator 'endsWith' is not supported because the required parameters might be missing. Try adding $count=true query parameter and ConsistencyLevel:eventual header. Refer to https://aka.ms/graph-docs/advanced-queries for more information",
"innerError": {
"date": "2023-07-14T08:43:39",
"request-id": "b3731da7-5c46-4c37-a8e5-b190124d2531",
"client-request-id": "a1556ddf-4794-929d-0105-b753a78b4c68"
}
}
}
Si una propiedad no se indexa para admitir un parámetro de consulta, la solicitud devuelve un error incluso si se especifican parámetros de consulta avanzados. Por ejemplo, la propiedad createdDateTime del recurso de grupo no se indexa para las funcionalidades de consulta.
GET https://graph.microsoft.com/beta/groups?$filter=createdDateTime ge 2021-11-01&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Groups.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "createdDateTime ge 2021-11-01";
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphgroups "github.com/microsoftgraph/msgraph-beta-sdk-go/groups"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestFilter := "createdDateTime ge 2021-11-01"
requestCount := true
requestParameters := &graphgroups.GroupsRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Count: &requestCount,
}
configuration := &graphgroups.GroupsRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
groups, err := graphClient.Groups().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
GroupCollectionResponse result = graphClient.groups().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "createdDateTime ge 2021-11-01";
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.groups.groups_request_builder import GroupsRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = GroupsRequestBuilder.GroupsRequestBuilderGetQueryParameters(
filter = "createdDateTime ge 2021-11-01",
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.groups.get(request_configuration = request_configuration)
{
"error": {
"code": "Request_UnsupportedQuery",
"message": "Unsupported or invalid query filter clause specified for property 'createdDateTime' of resource 'Group'.",
"innerError": {
"date": "2023-07-14T08:42:44",
"request-id": "b6a5f998-94c8-430d-846d-2eaae3031492",
"client-request-id": "2be83e05-649e-2508-bcd9-62e666168fc8"
}
}
}
Sin embargo, una solicitud que incluya parámetros de consulta podría producir un error silencioso. Por ejemplo, para parámetros de consulta no admitidos y para combinaciones no admitidas de parámetros de consulta. En estos casos, examine los datos devueltos por la solicitud para determinar si los parámetros de consulta especificados tuvieron el efecto deseado. Por ejemplo, el parámetro @odata.count falta aunque la consulta sea exitosa.
GET https://graph.microsoft.com/v1.0/users?$count=true
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Count = true;
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestCount := true
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Count: &requestCount,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.count = true;
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)