One of the major features introduced in Couchbase Lite 2.0, is the new Query interface based on N1QL, Couchbase’s declarative query language that extends SQL for JSON. If you are familiar with SQL, you will feel right at home with the semantics of the new API. We covered the basics of the interface in an earlier postagem no blog. Arrays are an integral component of modeling data with JSON. In this blog post, we will discuss querying of array collections using the new API.

This blog assumes you are familiar with the fundamentals, so if you haven’t done so already, be sure to review the postagem anterior first. The last section of the post lists links to other relevant query blogs.

You can download the Couchbase Mobile 2.0 Pre-release builds from our downloads página.

Histórico

Se você estava usando as versões 1.x do Couchbase Mobile, provavelmente está familiarizado com Visualizações de mapas para criar índices e consultas. Na versão 2.0, você não precisa mais criar visualizações e funções de mapa! Em vez disso, uma interface simples permite a criação de índices e você pode usar uma interface do Query Builder para construir suas consultas. A nova interface de consulta é mais simples de usar e muito mais poderosa em comparação. Vamos descobrir alguns de seus recursos nesta postagem.

Projeto de amostra

While the examples discussed here use Swift for iOS, note that barring some minor differences, the same query interface is supported on the Android and Windows platforms as well. So with some minor tweaks, you should be able to reuse the query examples in this post when working with other platforms.

Siga as instruções abaixo se você estiver interessado em um projeto Swift de amostra

  • Clone o iOS Swift Playground do GitHub

  • Siga as instruções de instalação no manual correspondente LEIAME para criar e executar o playground.

Modelo de dados de amostra

Usaremos o banco de dados Travel Sample localizado aqui

O conjunto de dados de amostra inclui vários tipos de documentos, conforme identificado pelo tipo no documento. Vamos nos concentrar em documentos de tipo "hotel" . The JSON document model is shown below. For brevity, we have omitted some of the properties from the model below.

Specifically, note that the model includes nested collections – public_likes e revisões. The queries in following sections will be dealing with these nested collections.

** Consulte o modelo acima para cada um dos exemplos de consulta abaixo. **

O identificador do banco de dados

Nas consultas abaixo, usaremos o Banco de dados API para abrir/criar o banco de dados CouchbaseLite.

Índices

Para acelerar as consultas de leitura, você pode criar índices nas propriedades que serão consultadas. A melhoria no desempenho seria significativa em grandes conjuntos de dados. Obviamente, esteja ciente de que haverá um aumento na necessidade de armazenamento para guardar os índices, e o desempenho das gravações também poderá ser afetado. Portanto, tenha cuidado ao criar muitos índices.

O exemplo a seguir cria um Índice de valor no tipo propriedade de um documento

O exemplo a seguir cria um Índice de valor em tipo e nome propriedades de um documento

Array Containment

The query below fetches the IDs, nomes e public_likes properties of documents where the public_likes array property in "hotel" tipo documents contains the value of “Corrine Hilll”. For this, the **ArrayFunction.contains** function expression is used on the public_likes array.

Array Size

The query below fetches the IDs, nomes properties and the tamanho de public_likes array property in "hotel" tipo documents. For this, the **ArrayFunction.length** function expression is used on the public_likes array to get the size of the array.

Also, notice that we are using como expression to alias the array count value to NumLikes. We had introduced aliases in the earlier blog post on Query Fundamentals. If you do not alias the result of the arrayLength expression, the property key would be $1 , which is not very intuitive.

Evaluating Array Members

Enquanto o ArrayFunction.contains function expression allows you to check if the given array contains a specific value, the em array expression can be used to evaluate any or all of the memebers of an array against a criteria specified by the satisfaz expression. This is a powerful document filtering capability.

Oemexpression is used with the qualquer, todos ou o anyAndEvery quantified operators on ArrayExpression to evaluate any, every or any/every element in the array object.

The following query returns the documents where qualquer of the values in the public_likes array begins with the characters “Corr”.

    1. Declare a variable with name “likedby” to represent every element in the public_likes matriz
    2. O qualquer ArrayExpression checks if the array element represented by the likedby variable satisfies the criteria in the como expression. The como expression checks if the value of the item represented by the “likedby” variable begins with “Cor”.

Indexing Arrays

You can also query elements at specific indexes. The following query returns the nome and first member of the public_likes array properties of all “hotel” documents

Evaluating Nested Arrays

You can evaluate the members a nested array. For this, you can apply a keypath to the variable expression. The nested array has to be one level deep.

The following query returns the documents where qualquer of the values in the nested classificações array has the Geral property rating that is greater than or equal to 4.
As you may have noted from the data model above, the “reviews” property holds an array of objects. Each of the objects contain a nested classificações array which in turn contains the Geral propriedade.

  1. Declare a variable to represent an element in the review.ratings.Overall matriz
  2. Declare a variable to represent every element in the revisões matriz
  3. O qualquer expression checks if the array element represented by the revisão variable satisfies the criteria in the comparação expression. The comparação expression checks the value of Geral property of the classificações array in the object represented by the “review” variable is greater than or equal to 4.

Limitações

The array manipulation capabilities are not nearly as extensive as N1QL’s feature set. But it’s a good starting point. These capabilities may be available in future releases of Couchbase Mobile.

So for now, it’s upto the app to manipulate the array results using the language’s collection processing capabilities.

Let’s consider this example in swift

  • Referring to the data model, let’s say you wanted to determine the mínimo Limpeza rating for a given hotel based on the reviews on the hotel.

From the model above , note that the Limpeza property is a member of the the classificações property contained in each object that is member of revisões array.

For this, you can do a Couchbase Lite query to fetch the revisões array property for a hotel with specified Id as follows –

O resultSet response to the above query would be an array with a single element. This element would correspond to the “hotel” document for the specified Id.

Now, the app has to implement the logic to iterate over the revisões array and for each member of the array, to fetch the classificações property and corresponding Limpeza valor.

Here is one possible way to do it in swift.

  • First, iterate over the resultSet and extract the value of “reviews” property.

After the loop processing, the “matches” array would be something like the one below. It would be an array containing the nested array corresponding to the reviews –

  • You can then use swift language features like flatMap e mapa to process the resulting array to derive the minimum “Cleanliness” rating for given hotel

You would do something similar in languages that support functional constructs like mapa plano e mapa.

O que vem a seguir

This blog post looked at how you can handle Array collection types using the new Query API in Couchbase Mobile 2.0. This is a start. Expect to see more functionality in future releases. You can download the Pre-release build from our downloads página.

Aqui estão outras postagens relacionadas ao Couchbase Mobile Query que podem ser de interesse
- Isso postagem no blog discusses the fundamentals of the Query API
- Isso postagem no blog discute os recursos de pesquisa de texto completo.
- Isso postagem no blog discute como fazer consultas JOIN

Se tiver dúvidas ou comentários, deixe um comentário abaixo ou entre em contato comigo pelo Twitter @rajagp ou envie-me um e-mail priya.rajagopal@couchbase.com. O Fóruns do Couchbase são outro bom lugar para entrar em contato com perguntas.

Autor

Postado por Priya Rajagopal, Diretora Sênior, Gerenciamento de Produtos

Priya Rajagopal é diretora sênior de gerenciamento de produtos da Couchbase, responsável pelas plataformas de desenvolvedor para a nuvem e a borda. Ela desenvolve software profissionalmente há mais de 20 anos em vários cargos técnicos e de liderança de produtos, com mais de 10 anos de foco em tecnologias móveis. Como delegada de padrões de IPTV da TISPAN, ela foi uma das principais colaboradoras das especificações de padrões de IPTV. Ela tem 22 patentes nas áreas de rede e segurança de plataforma.

Deixar uma resposta