Usar operaciones de consulta de OData en solicitudes REST de SharePointUse OData query operations in SharePoint REST requests

Antes de comenzarBefore you start

El servicio REST de SharePoint admite una amplia variedad de operadores de cadenas de consultas OData que permiten seleccionar, filtrar y ordenar los datos solicitados.The SharePoint REST service supports a wide range of OData query string operators that enable you to select, filter, and order the data you request.

Sugerencia

El servicio REST de SharePoint Online (y SharePoint 2016 local o versiones posteriores) admite la combinación de varias solicitudes en una sola llamada al servicio mediante la opción de consulta $batch de OData. Para obtener más información y vínculos a los ejemplos de código, vea Realizar solicitudes de lote con las API REST.The SharePoint Online (and on-premises SharePoint 2016 and later) REST service supports combining multiple requests into a single call to the service by using the OData $batch query option. For details and links to code samples, see Make batch requests with the REST APIs.

Seleccionar los campos para devolverSelect fields to return

Use la opción de consulta $select para especificar los campos que se devolverán para una lista, un elemento de lista u otro objeto de SharePoint concretos que se representen mediante un conjunto de entidades. Puede usar $select=* para devolver todos los campos disponibles.Use the $select query option to specify which fields to return for a given list, list item, or other SharePoint object represented by an entity set. You can use $select=* to return all available fields.

Nota

In general, if you do not specify the $select query option, the REST service returns all available fields by default. However, in a few cases, some SharePoint objects include properties that are very resource intensive to retrieve; to optimize REST service performance, these properties are not included in the default query, and must be explicitly requested.For example, the SPWeb.EffectiveBasePermissions property is not returned by default, and must be explicitly requested by using the $select query option.In general, if you do not specify the $select query option, the REST service returns all available fields by default. However, in a few cases, some SharePoint objects include properties that are very resource intensive to retrieve; to optimize REST service performance, these properties are not included in the default query, and must be explicitly requested.For example, the SPWeb.EffectiveBasePermissions property is not returned by default, and must be explicitly requested by using the $select query option.

También, puede especificar que la solicitud devuelva campos proyectados de otras listas y los valores de búsquedas. Para ello, especifique el nombre de campo en las opciones de consulta $select y $expand. Por ejemplo:In addition, you can specify that the request returns projected fields from other lists and the values of lookups. To do this, specify the field name in both the $select and $expand query options. For example:

http://server/site/_api/web/lists('guid')/items?$select=Title,Products/Name&$expand=Products/Name

No se admiten la expansión y selección masivas de elementos relacionados.Bulk expansion and selection of related items is not supported.

Seleccionar los elementos para devolverSelect items to return

Use la opción de consulta $filter para seleccionar los elementos que se devolverán. En la sección Operadores de consultas de OData compatibles con el servicio REST de SharePoint se enumeran las opciones y funciones de comparación de consultas de filtro que se pueden usar con el servicio REST de SharePoint.Use the $filter query option to select which items to return. OData query operators supported in the SharePoint REST service lists the filter query comparison options and functions you can use with the SharePoint REST service.

Consulta para campos de búsqueda de valores únicosQuery for single value lookup fields

Los campos de búsqueda de valores únicos se representan con dos campos separados en el servicio REST de SharePoint: un campo representa al valor de campo real, y otro representa al nombre del campo. Puede hacer consultas con el valor del campo de búsqueda tal como lo haría con cualquier otro campo de ese tipo de datos. Por ejemplo, si el valor del campo de búsqueda es una cadena, puede usar opciones de comparación de cadenas en la consulta.Single value lookup fields are represented by two separate fields in the SharePoint REST service: one field representing the actual field value, and another representing the field name. You can perform queries against the lookup field value as you would any other field of that data type. For example, if the lookup field value is a string, you can use string comparison options in your query.

Consulta para usuariosQuery for users

En el servicio REST de SharePoint, los usuarios están representados con el nombre (visualización) de usuario fácil de recordar, y no sus alias o combinación dominio\alias. Por lo tanto, construya consultas de usuario con los nombres de usuario fáciles de recordar.In the SharePoint REST service, users are represented by the user's friendly (display) name, and not their alias or domain\alias combination. Therefore, you must construct user queries against users' friendly names.

Nota

Membership-based user queries are not supported. Usage of the Current operator to do queries using the ID of the current user is not supported.Membership-based user queries are not supported. Usage of the Current operator to do queries using the ID of the current user is not supported.

Consulta de usuarios y campos de búsqueda de varios valoresQuery for multi-value lookup fields and users

Dado que los campos de búsqueda de varios valores son devueltos como una cadena de varios valores, no existe una manera de consultarlos (por ejemplo, no se admite el equivalente de un elemento Includes o un elemento NotIncludes).Because multi-value lookup fields are returned as a string of multiple values, there is no way to query for them (for example, the equivalent of an Includes element or NotIncludes element is not supported).

Ordenar elementos devueltosSort returned items

Use the $orderby query option to specify how to sort the items in your query return set. To sort by multiple fields, specify a comma-separated list of fields. You can also specify whether to sort the items in ascending or descending order by appending the asc or desc keyword to your query.Use the $orderby query option to specify how to sort the items in your query return set. To sort by multiple fields, specify a comma-separated list of fields. You can also specify whether to sort the items in ascending or descending order by appending the asc or desc keyword to your query.

Pasar de una página a otra en elementos devueltosPage through returned items

Use las opciones de consulta $top y $skiptoken para seleccionar un subconjunto de los elementos que, de lo contrario, devolvería la consulta.Use the $top and $skiptoken query options to select a subset of the items that would otherwise be returned by your query.

Nota

La opción de consulta $skip no funciona con consultas para elementos de lista de SharePoint.The $skip query option does not work with queries for SharePoint list items.

La opción $top le permite seleccionar para devolver los primeros n elementos del conjunto de devolución. Por ejemplo, la siguiente URI solicita que realmente se devuelvan solo los primeros diez elementos del conjunto de devolución posible:The $top option enables you to select the first n items of the return set for return. For example, the following URI requests that only the first ten items in the prospective return set actually be returned:

http://server/site/_api/web/lists('<guid>')/items?$top=10

La opción $skiptoken le permite omitir elementos hasta llegar al elemento especificado y devolver el resto.The $skiptoken option enables you to skip over items until the specified item is reached and return the rest.

?$skiptoken=Paged=TRUE%26p_ID=5

Nota

When using these query options, take into account that paging in OData is ordinal. For example, suppose you are implementing a next page button to display SharePoint list items. You use the REST service to enable the button to return items 1 through 20 when clicked, and then items 21 through 40, and so on. However, suppose another user deletes items 4 and 18 between clicks of the next button. In such a case, the ordinal positioning of the remaining items is reset, and displaying items 21 through 40 actually skips over two items.When using these query options, take into account that paging in OData is ordinal. For example, suppose you are implementing a next page button to display SharePoint list items. You use the REST service to enable the button to return items 1 through 20 when clicked, and then items 21 through 40, and so on. However, suppose another user deletes items 4 and 18 between clicks of the next button. In such a case, the ordinal positioning of the remaining items is reset, and displaying items 21 through 40 actually skips over two items.

Operadores de consultas de OData compatibles con el servicio REST de SharePointOData query operators supported in the SharePoint REST service

AdmitidoSupported No admitidoNot supported
Comparaciones numéricas Lt Le Gt Ge Eq NeNumeric comparisons Lt Le Gt Ge Eq Ne **Operadores aritméticos ** (Add, Sub, Mul, Div, Mod)Arithmetic operators (Add, Sub, Mul, Div, Mod)
**Funciones matemáticas básicas ** (round, floor, ceiling)Basic math functions (round, floor, ceiling)
Comparaciones de cadenas startsWith substringof Eq NeString comparisons startsWith substringof Eq Ne endsWith replace substring tolower toupper trim concatendsWith replace substring tolower toupper trim concat
Funciones de fecha y hora day() month() year() hour() minute() second()Date and time functions day() month() year() hour() minute() second() Operador DateTimeRangesOverlapDateTimeRangesOverlap operator
Consultar si una fecha y hora cae dentro de un patrón de fecha y hora recurrente.Querying as to whether a date time falls inside a recurrent date time pattern

En la ilustración siguiente se muestran las opciones de consultas OData admitidas.The following figure shows the supported OData query options.

Opciones de consultas OData admitidasSupported OData query options

Sintaxis de opción de consulta de servicio REST de SharePoint


Vea tambiénSee also