MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/nodejs-docs-samples / main

Function main

spanner/index-query-data.js:21–83  ·  view source on GitHub ↗
(
  instanceId = 'my-instance',
  databaseId = 'my-database',
  projectId = 'my-project-id',
  startTitle = 'Ardvark',
  endTitle = 'Goo'
)

Source from the content-addressed store, hash-verified

19'use strict';
20
21function main(
22 instanceId = 'my-instance',
23 databaseId = 'my-database',
24 projectId = 'my-project-id',
25 startTitle = 'Ardvark',
26 endTitle = 'Goo'
27) {
28 // [START spanner_query_data_with_index]
29 /**
30 * TODO(developer): Uncomment these variables before running the sample.
31 */
32 // const instanceId = 'my-instance';
33 // const databaseId = 'my-database';
34 // const projectId = 'my-project-id';
35 // const startTitle = 'Ardvark';
36 // const endTitle = 'Goo';
37
38 // Imports the Google Cloud Spanner client library
39 const {Spanner} = require('@google-cloud/spanner');
40
41 // Instantiates a client
42 const spanner = new Spanner({
43 projectId: projectId,
44 });
45
46 async function queryDataWithIndex() {
47 // Gets a reference to a Cloud Spanner instance and database
48 const instance = spanner.instance(instanceId);
49 const database = instance.database(databaseId);
50
51 const query = {
52 sql: `SELECT AlbumId, AlbumTitle, MarketingBudget
53 FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}
54 WHERE AlbumTitle >= @startTitle AND AlbumTitle <= @endTitle`,
55 params: {
56 startTitle: startTitle,
57 endTitle: endTitle,
58 },
59 };
60
61 // Queries rows from the Albums table
62 try {
63 const [rows] = await database.run(query);
64
65 rows.forEach(row => {
66 const json = row.toJSON();
67 const marketingBudget = json.MarketingBudget
68 ? json.MarketingBudget
69 : null; // This value is nullable
70 console.log(
71 `AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}, MarketingBudget: ${marketingBudget}`
72 );
73 });
74 } catch (err) {
75 console.error('Failed to query data with index:', err.message || err);
76 } finally {
77 // Close the database when finished.
78 await database.close();

Callers 1

Calls 1

queryDataWithIndexFunction · 0.85

Tested by

no test coverage detected