Comparteix a través de


Paginar resultados mediante FetchXml

Puede especificar un límite en la cantidad de filas recuperadas para cada solicitud estableciendo un tamaño de página. Al utilizar la paginación, puede recuperar páginas consecutivas de datos que representan todos los registros que coinciden con los criterios de una consulta de manera eficaz.

El tamaño de página predeterminado y máximo es 5000 filas. Si no establece un tamaño de página, Dataverse devolverá hasta 5000 filas de datos a la vez. Para obtener más filas, debe enviar solicitudes adicionales.

Nota

Modelos de paginación

Dataverse tiene dos modelos de paginación: simple y usando cookies de paginación:

Sencillo

  • Utiliza solo los atributos elemento de búsqueda count y page
  • Adecuado solo para conjuntos de datos pequeños
  • No se puede devolver un conjunto de datos de más de 50.000 registros
  • El rendimiento se reduce a medida que aumenta el número de filas

Cookies de paginación

Paginación sencilla

Puede solicitar la primera página configurando el atributo elemento de búsqueda page en 1 y el atributo count al tamaño de la página antes de enviar la solicitud:

<fetch count='3' page='1'>
  <entity name='account'>
    <attribute name='name' />
    <order attribute='name' />
    <order attribute='accountid' />
  </entity>
</fetch>

Para obtener los siguientes tres registros, incremente el valor de page y envíe otra solicitud.

<fetch count='3' page='2'>
  <entity name='account'>
    <attribute name='name' />
    <order attribute='name' />
    <order attribute='accountid' />    
  </entity>
</fetch>

Con una paginación simple, a veces denominada paginación heredada, Dataverse recupera todos los resultados de la consulta hasta la página actual, selecciona el número de registros necesarios para la página y después ignora el resto. Esto permite retroceder y avanzar rápidamente entre los datos o saltar a una página específica. Sin embargo, el número total de registros está limitado a 50.000 y puede haber problemas de rendimiento para consultas complejas y resultados de consultas distintos ordenados arbitrariamente.

La paginación simple funciona bien para conjuntos de datos pequeños, pero a medida que aumenta el número de filas en conjunto de datos, el rendimiento se ve afectado. El número total de filas que se pueden recuperar mediante paginación simple es 50.000. Para obtener el mejor rendimiento en todos los casos, recomendamos utilizar cookies de paginación de forma constante.

Cookies de paginación

Cuando hay más filas para recuperar después de solicitar la primera página, Dataverse normalmente devuelve una cookie de paginación que se utilizará en las siguientes solicitudes para las páginas siguientes.

La cookie de paginación contiene datos sobre el primer y último registro de los resultados y ayuda a Dataverse a recuperar la siguiente fila de datos lo más rápido posible y debe usarse cuando se proporciona. No debe modificar los datos en la cookie de paginación, simplemente establezca el valor en el atributo elemento de búsqueda paging-cookie e incremente el valor del atributo page para solicitudes posteriores.

Consultas que no admiten cookies de paginación

Algunas consultas no admiten cookies de paginación. Cuando una consulta no admite cookies de paginación, no se devuelve ningún valor de cookie de paginación con el resultado. Por ejemplo, es posible que las consultas ordenadas mediante un atributo link-entity no admitan cookies de paginación.

Cuando Dataverse no devuelve una cookie de paginación, el modelo de paginación vuelve a la paginación simple, con todas las limitaciones que conlleva.

La forma de utilizar cookies de paginación depende de si utiliza el SDK para .NET o API web.

El siguiente método estático RetrieveAll devolverá todos los registros que coincidan con la consulta FetchXml y enviará múltiples solicitudes si la cantidad de registros excede el tamaño de la página.

Después de cada solicitud, el método comprueba la Propiedad EntityCollection.MoreRecords para determinar si más registros coinciden con los criterios. Si hay más registros, el método establece el valor de la Propiedad EntityCollection.PagingCookie devuelta en el atributo paging-cookie de elemento fetch y envía otra solicitud.

/// <summary>
/// Returns all records matching the criteria
/// </summary>
/// <param name="service">The authenticated IOrganizationService instance.</param>
/// <param name="fetchXml">The fetchXml Query string</param>
/// <param name="pageSize">The page size to use. Default is 5000</param>
/// <returns>All the records that match the criteria</returns>
static EntityCollection RetrieveAll(IOrganizationService service, string fetchXml, int pageSize = 5000)
{

    // The records to return
    List<Entity> entities = new();

    XElement fetchNode = XElement.Parse(fetchXml);

    int page = 1; //Start with page 1

    //Set the page
    fetchNode.SetAttributeValue("page", page);

    // Set the page size
    fetchNode.SetAttributeValue("count", pageSize);

    while (true)
    {
        // Get the page
        EntityCollection results = service.RetrieveMultiple(new FetchExpression(fetchNode.ToString()));

        entities.AddRange(results.Entities);

        if (!results.MoreRecords)
        {
            break;
        }

        // Set the fetch paging-cookie attribute with the paging cookie from the previous query
        fetchNode.SetAttributeValue("paging-cookie", results.PagingCookie);

        fetchNode.SetAttributeValue("page", page++);
    }
    return new EntityCollection(entities);
}

Puede adaptar el ejemploInicio rápido: ejecutar una solicitud de SDK para .NET (C#) para probar consultas FetchXml con los siguientes pasos:

  1. Agregue el método estático RetrieveAll a la clase Program.
  2. Modifique el método Main como se muestra a continuación:
static void Main(string[] args)
{
    using (ServiceClient serviceClient = new(connectionString))
    {
        if (serviceClient.IsReady)
        {
            //WhoAmIResponse response = 
            //    (WhoAmIResponse)serviceClient.Execute(new WhoAmIRequest());

            //Console.WriteLine("User ID is {0}.", response.UserId);

            string fetchQuery = @"<fetch count='3' page='1'>
                <entity name='contact'>
                    <attribute name='fullname'/>
                    <attribute name='jobtitle'/>
                    <attribute name='annualincome'/>
                    <order descending='true' attribute='fullname'/>
                </entity>
        </fetch>";

            EntityCollection records = RetrieveAll(service: serviceClient,
                        fetchXml: fetchQuery,
                        pageSize: 25);

            Console.WriteLine($"Success: {records.Entities.Count}");
        }
        else
        {
            Console.WriteLine(
                "A web service connection was not established.");
        }
    }

    // Pause the console so it does not close.
    Console.WriteLine("Press the <Enter> key to exit.");
    Console.ReadLine();
}

Importante

Esta consulta devolverá TODOS los registros que coincidan con los criterios. Asegúrese de incluir elementos de filtro para limitar los resultados.

Ordering and paging

How a page is ordered makes a big difference when paging data. If the information about how the results are ordered is ambiguous, Dataverse can't consistently or efficiently return paged data.

Specify an order for your query. With FetchXml, if you don't add any order elements to your query, Dataverse adds an order based on the primary key of the table. However QueryExpression does not, and when your query specifies distinct results, no primary key values are returned, so Dataverse can't add this default order. You must specify a paging order. Without any order specified, distinct query results might be returned in random order. OData doesn't provide any option to return distinct results, but you should still apply an order when retrieving paged results.

Paging is dynamic. Each request is evaluated independently as they're received. A paging cookie tells Dataverse the previous page. With this paging cookie data, Dataverse can start with the next record after the last one on the preceding page.

Paging works best going forward. If you go back and retrieve a page you previously retrieved, the results can be different because records could be added, deleted, or modified during since you last retrieved the page. In other words, if your page size is 50 and you go back, you get 50 records, but they might not be the same 50 records. If you keep progressing forward through the pages of a data set, you can expect all the records are returned in a consistent sequence.

Deterministic ordering is important

Deterministic ordering means that there's a way to calculate an order consistently. With a given set of records, the records are always returned in the same order. If you need consistent orders and paging, you must include some unique values or combination of column values that are and specify an order for them to be evaluated.

Nondeterministic example

Let's look at an example that is nondeterministic. This data set contains only State and Status information and is filtered to only return records in an open State. The results are ordered by Status. The first three pages are requested. The results look like this:

State Status Page
Open Active 1 Start
Open Active 1
Open Active 1 End
Open Active
Open Active
Open Inactive
Open Inactive

The paging cookie saves information about the last record on the page. When the next page is requested, the last record from the first page isn't included. However, given the nondeterministic data, there's no guarantee that the other two records on the first page aren't included in the second page.

To achieve deterministic ordering, add orders on columns that contain unique values, or values that are semi-unique.

Deterministic example

This query is like the nondeterministic one, but it includes the Case ID column that includes unique values. It's also ordered by Status, but also ordered using Case ID. The results look like this:

State Status Case ID Page
Open Active Case-0010 1 Start
Open Active Case-0021 1
Open Active Case-0032 1 End
Open Active Case-0034
Open Active Case-0070
Open Inactive Case-0015
Open Inactive Case-0047

In the next page, the cookie will have Case-0032 stored as the last record in the first page, so page two will start with the next record after that record. The results look like this:

State Status Case ID Page
Open Active Case-0010 1 Start
Open Active Case-0021 1
Open Active Case-0032 1 End
Open Active Case-0034 2 Start
Open Active Case-0070 2
Open Inactive Case-0015 2 End
Open Inactive Case-0047

Because this query orders unique column values, the order is consistent.

Best practices for orders when paging data

Nota

When possible, queries should order on the primary key for the table because Dataverse is optimized for ordering on the primary key by default. Ordering by non-unique or complex fields cause excess overhead and slower queries.

When you retrieve a limited set of data to display in an application, or if you need to return more than 5,000 rows of data, you need to page the results. The choices you make in determining the order of the results can determine whether the rows in each page of data you retrieve overlaps with other pages. Without proper ordering, the same record can appear in more than one page.

To prevent the same record from appearing in more than one page, apply the following best practices:

It's best to include a column that has a unique identifier. For example:

  • Table primary key columns
  • Autonumber columns
  • User/contact IDs

If you can't include a column with a unique identifier, include multiple fields that will most likely result in unique combinations. For example:

  • First name + last name + email address
  • Full name + email address
  • Email address + company name

Anti-patterns for orders when paging data

The following are ordering choices to avoid:

  • Orders that don't include unique identifiers

  • Orders on calculated fields

  • Orders that have single or multiple fields that aren't likely to provide uniqueness such as:

    • Status and state
    • Choices or Yes/No
    • Name values by themselves. For example name, firstname, lastname
    • Text fields like titles, descriptions, and multi-line text
    • Non unique number fields

Pasos siguientes

Aprenda a agregar datos.

Nota

¿Puede indicarnos sus preferencias de idioma de documentación? Realice una breve encuesta. (tenga en cuenta que esta encuesta está en inglés)

La encuesta durará unos siete minutos. No se recopilan datos personales (declaración de privacidad).