Cómo usar la búsqueda por texto

Usa las funciones de búsqueda de texto en Cloud Firestore para buscar cadenas específicas dentro de los documentos.

Requisitos de la edición

La búsqueda de texto requiere una base de datos de la edición Enterprise de Firestore.

Antes de comenzar

Para realizar una búsqueda de texto, primero debes crear índices de texto para los campos en los que necesitas buscar.

Para realizar una búsqueda de texto, usa la expresión documentMatches dentro del parámetro query de la etapa search(...).

La operación solo busca en los campos indexados con un índice de texto. Si hay varios índices disponibles, Cloud Firestore selecciona un índice para usar en la operación.

Web

const result = await execute(db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('waffles')
  }));
iOS
let snapshot = try await db.pipeline().collection("restaurants")
  .search(query: DocumentMatches("waffles"))
  .execute()

Kotlin

val pipeline = db.pipeline().collection("restaurants")
    .search(SearchStage.withQuery(documentMatches("waffles")))

Java

Pipeline pipeline = db.pipeline().collection("restaurants")
        .search(SearchStage.withQuery(documentMatches("waffles")));
Node.js
await db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('waffles')
  })
  .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import DocumentMatches

results = (
    client.pipeline()
    .collection("restaurants")
    .search(DocumentMatches("waffles"))
    .execute()
)
Java
Pipeline.Snapshot results1 =
    firestore.pipeline().collection("restaurants")
        .search(Search.withQuery(documentMatches("waffles")))
        .execute().get();
Go
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("waffles"))).
	Execute(ctx)

Busca un término exacto

Para buscar un término exacto, encierra el término entre comillas ("):

Web

const result = await execute(db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('"belgian waffles"')
  }));
iOS
let snapshot = try await db.pipeline().collection("restaurants")
  .search(query: DocumentMatches("\"belgian waffles\""))
  .execute()

Kotlin

val pipeline = db.pipeline().collection("restaurants")
    .search(SearchStage.withQuery(documentMatches("\"belgian waffles\"")))

Java

Pipeline pipeline = db.pipeline().collection("restaurants")
        .search(SearchStage.withQuery(documentMatches("\"belgian waffles\"")));
Node.js
await db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('"belgian waffles"')
  })
  .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import DocumentMatches

results = (
    client.pipeline()
    .collection("restaurants")
    .search(DocumentMatches('"belgian waffles"'))
    .execute()
)
Java
Pipeline.Snapshot results2 =
    firestore.pipeline().collection("restaurants")
        .search(Search.withQuery(documentMatches("\"belgian waffles\"")))
        .execute().get();
Go
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("\"belgian waffles\""))).
	Execute(ctx)

Busca una combinación de términos

Para buscar una combinación de términos (lógica AND), separa los términos con espacios:

Web

const result = await execute(db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('waffles eggs')
  }));
iOS
let snapshot = try await db.pipeline().collection("restaurants")
  .search(query: DocumentMatches("waffles eggs"))
  .execute()

Kotlin

val pipeline = db.pipeline().collection("restaurants")
    .search(SearchStage.withQuery(documentMatches("waffles eggs")))

Java

Pipeline pipeline = db.pipeline().collection("restaurants")
        .search(SearchStage.withQuery(documentMatches("waffles eggs")));
Node.js
await db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('waffles eggs')
  })
  .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import DocumentMatches

results = (
    client.pipeline()
    .collection("restaurants")
    .search(DocumentMatches("waffles eggs"))
    .execute()
)
Java
firestore.collection("restaurants").add(new HashMap<String, Object>() {{
  put("name", "Morning Diner");
  put("description", "Start your day with waffles and eggs.");
}});
Pipeline.Snapshot results3 =
    firestore.pipeline().collection("restaurants")
        .search(Search.withQuery(documentMatches("waffles eggs")))
        .execute().get();
Go
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("waffles eggs"))).
	Execute(ctx)

Excluye un término

Para excluir un término, antepón un guion (-):

Web

const result = await execute(db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('coffee -waffles')
  }));
iOS
let snapshot = try await db.pipeline().collection("restaurants")
  .search(query: DocumentMatches("coffee -waffles"))
  .execute()

Kotlin

val pipeline = db.pipeline().collection("restaurants")
    .search(SearchStage.withQuery(documentMatches("waffles eggs")))

Java

Pipeline pipeline = db.pipeline().collection("restaurants")
        .search(SearchStage.withQuery(documentMatches("coffee -waffles")));
Node.js
await db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('-waffles')
  })
  .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import DocumentMatches

results = (
    client.pipeline()
    .collection("restaurants")
    .search(DocumentMatches("-waffles"))
    .execute()
)
Java
firestore.collection("restaurants").add(new HashMap<String, Object>() {{
  put("name", "City Coffee");
  put("description", "Premium coffee and pastries.");
}});
Pipeline.Snapshot results4 =
    firestore.pipeline().collection("restaurants")
        .search(Search.withQuery(documentMatches("-waffles")))
        .execute().get();
Go
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("-waffles"))).
	Execute(ctx)

También puedes excluir una frase, por ejemplo, pizza -"New York".

Ordenar resultados

De forma predeterminada, Cloud Firestore ordena los resultados por hora de creación del documento, del más reciente al más antiguo. En su lugar, puedes ordenar por puntuación de búsqueda, pero esto requiere más procesamiento para calcular y comparar la puntuación exacta de cada documento:

Para ordenar los resultados por puntuación de búsqueda, haz lo siguiente:

Web

const result = await execute(db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('waffles'),
    sort: score().descending()
  }));
iOS
let snapshot = try await db.pipeline().collection("restaurants")
  .search(
      query: DocumentMatches("waffles"),
      sort: [Score().descending()]
      )
  .execute()

Kotlin

val pipeline = db.pipeline().collection("restaurants")
    .search(SearchStage
              .withQuery(documentMatches("waffles"))
              .withSort(score().descending())
              )
Node.js
await db.pipeline().collection('restaurants')
  .search({
    query: documentMatches('waffles'),
    sort: score().descending()
  })
  .execute();

Agrega campos a los documentos que muestra la etapa de búsqueda

Puedes usar addFields para agregar campos a los documentos que muestra la etapa de búsqueda. Las expresiones que muestran valores calculados por la etapa de búsqueda, como score(), se pueden usar dentro de addFields en la etapa de búsqueda para escribir esos `values en los documentos de salida.

En el siguiente ejemplo, se agrega el campo de puntuación a los documentos que muestra la etapa de búsqueda:

Web

const result = await execute(db.pipeline().collection('restaurants')
  .search({
    query: 'menu:waffles',
    addFields: [
        score().as('score'),
    ]
  }));
iOS
let snapshot = try await db.pipeline().collection("restaurants")
  .search(
    query: DocumentMatches("waffles"),
    addFields: [
      Score().as("score")
    ]
  )
  .execute()

Kotlin

val pipeline = db.pipeline().collection("restaurants")
    .search(SearchStage.withQuery(documentMatches("waffles eggs")))

Java

Pipeline pipeline = db.pipeline().collection("restaurants")
        .search(
                SearchStage.withQuery(documentMatches("menu:waffles"))
                        .withAddFields(score().alias("score")));
Node.js
await db.pipeline().collection('restaurants')
  .search({
    query: field('menu').matches('waffles'),
    addFields: [
        score().as('score'),
    ]
  }).execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import DocumentMatches, Score
from google.cloud.firestore_v1.pipeline_stages import SearchOptions

results = (
    client.pipeline()
    .collection("restaurants")
    .search(
        SearchOptions(
            query=DocumentMatches("menu:waffles"),
            add_fields=[Score().as_("score")],
        )
    )
    .execute()
)
Java
Pipeline.Snapshot results5 =
    firestore.pipeline().collection("restaurants")
        .search(Search.withQuery(field("menu").regexMatch("waffles"))
            .withAddFields(score().as("score")))
        .execute().get();
Go
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(
		firestore.WithSearchQuery(firestore.FieldOf("menu").RegexMatch("waffles")),
		firestore.WithSearchAddFields(firestore.Score().As("score")),
	).
	Execute(ctx)