Sử dụng tính năng tìm kiếm bằng văn bản

Sử dụng các tính năng tìm kiếm văn bản trong Cloud Firestore để tìm kiếm các chuỗi cụ thể trong tài liệu.

Yêu cầu đối với phiên bản

Tính năng tìm kiếm văn bản yêu cầu cơ sở dữ liệu Firestore Enterprise Edition.

Trước khi bắt đầu

Để thực hiện tìm kiếm văn bản, trước tiên, bạn phải tạo chỉ mục văn bản cho các trường mà bạn cần tìm kiếm.

Để thực hiện tìm kiếm văn bản, hãy dùng biểu thức documentMatches trong tham số query của giai đoạn search(...).

Thao tác này chỉ tìm kiếm trong các trường được lập chỉ mục bằng chỉ mục văn bản. Nếu có nhiều chỉ mục, Cloud Firestore sẽ chọn một chỉ mục để sử dụng cho thao tác.

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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("waffles"))).
	Execute(ctx)

Tìm kiếm một cụm từ chính xác

Để tìm kiếm một cụm từ chính xác, hãy đặt cụm từ đó trong dấu ngoặc kép ("):

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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("\"belgian waffles\""))).
	Execute(ctx)

Tìm kiếm một tổ hợp cụm từ

Để tìm kiếm tổ hợp các cụm từ (toán tử logic AND), hãy tách các cụm từ bằng dấu cách:

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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("waffles eggs"))).
	Execute(ctx)

Loại trừ một từ khoá

Để loại trừ một cụm từ, hãy thêm dấu gạch nối (-) vào trước cụm từ đó:

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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(firestore.WithSearchQuery(firestore.DocumentMatches("-waffles"))).
	Execute(ctx)

Bạn cũng có thể loại trừ một cụm từ, ví dụ: pizza -"New York".

Phân loại kết quả

Theo mặc định, Cloud Firestore kết quả được sắp xếp theo thời gian tạo tài liệu, từ mới nhất đến cũ nhất. Bạn có thể sắp xếp theo điểm tìm kiếm, nhưng việc này đòi hỏi nhiều phép tính hơn để tính toán và so sánh điểm số chính xác của từng tài liệu:

Cách sắp xếp kết quả theo điểm tìm kiếm:

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();

Thêm các trường vào tài liệu do giai đoạn tìm kiếm trả về

Bạn có thể dùng addFields để thêm các trường vào tài liệu do giai đoạn tìm kiếm trả về. Các biểu thức trả về giá trị do giai đoạn tìm kiếm tính toán, chẳng hạn như score(), có thể được dùng trong addFields ở giai đoạn tìm kiếm để ghi những "giá trị" đó vào các tài liệu đầu ra.

Ví dụ sau đây sẽ thêm trường điểm vào các tài liệu do giai đoạn tìm kiếm trả về:

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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("restaurants").
	Search(
		firestore.WithSearchQuery(firestore.FieldOf("menu").RegexMatch("waffles")),
		firestore.WithSearchAddFields(firestore.Score().As("score")),
	).
	Execute(ctx)