תיאור מפורט של פונקציות אריתמטיות

פונקציות אריתמטיות

לכל הפונקציות האריתמטיות ב-Firestore יש את ההתנהגויות הבאות:

  • הפונקציה מחזירה את הערך NULL אם אחד מהפרמטרים של הקלט הוא NULL.
  • הפונקציה מחזירה את הערך NaN אם אחד מהארגומנטים הוא NaN.
  • יוצרת שגיאה אם מתרחשת גלישה חיובית או גלישה שלילית.

מערכת Firestore מבצעת הרחבה של סוגים מספריים על סמך ההיררכיה הבאה: INT32 < INT64 < FLOAT64 < DECIMAL128. כשפונקציה אריתמטית מקבלת כמה ארגומנטים מספריים מסוגים שונים (לדוגמה, add(5.0D, 6L)), סוגים צרים יותר מומרים באופן מרומז לסוג הרחב ביותר שקיים בין האופרנדים. בדוגמה הקודמת, ה-6L הורחב ל-6.0D, ולכן הביטוי מחזיר סוג FLOAT64.

המרת טיפוס משתנה מ-INT64 ל-FLOAT64 יכולה לגרום לאובדן דיוק, כי הערך המומר עלול לאבד את הביטים הכי פחות משמעותיים שלו. הערך שיתקבל יהיה גרסה מעוגלת של ערך המספר השלם המקורי, באמצעות מצב העיגול הקרוב ביותר של IEEE 754.

שם תיאור
ABS הפונקציה מחזירה את הערך המוחלט של number
ADD מחזירה את הערך של x + y
SUBTRACT מחזירה את הערך של x - y
MULTIPLY מחזירה את הערך של x * y
DIVIDE הפונקציה מחזירה את הערך של x / y
MOD הפונקציה מחזירה את השארית של חלוקת x / y
CEIL הפונקציה מחזירה את הערך הקטן ביותר שגדול או שווה ל-number
FLOOR הפונקציה מחזירה את הערך התחתון של number
ROUND מעגל number ל-places ספרות אחרי הנקודה העשרונית
TRUNC חיתוך של number ל-places ספרות אחרי הנקודה העשרונית
POW הפונקציה מחזירה את הערך של base^exponent
SQRT הפונקציה מחזירה את השורש הריבועי של number
EXP הפונקציה מחזירה את מספר אוילר בחזקת exponent
LN הפונקציה מחזירה את הלוגריתם הטבעי של number
LOG הפונקציה מחזירה את הלוגריתם של number
LOG10 הפונקציה מחזירה את הלוגריתם של number בבסיס 10
RAND הפונקציה מחזירה מספר אקראי לכאורה בשיטת נקודה צפה

ABS

תחביר:

abs[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N

תיאור:

הפונקציה מחזירה את הערך המוחלט של number.

  • הפונקציה מחזירה שגיאה אם היא גורמת לגלישה של ערך INT32 או INT64.

לדוגמה:

מספר abs(number)
10 10
-10 10
10L 10L
‫-0.0 0.0
10.5 10.5
-10.5 10.5
-231 [error]
‫‎-263 [error]

הוספה

תחביר:

add[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

תיאור:

הפונקציה מחזירה את הערך של x + y.

לדוגמה:

x y add(x, y)
20 3 23
‫10.0 1 11.0
22.5 2.0 24.5
INT64.MAX 1 [error]
INT64.MIN -1 [error]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks"))
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("soldBooks").add(Field("unsoldBooks")).as("totalBooks")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks"))
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("soldBooks").add(Field.of("unsoldBooks")).as_("totalBooks"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(add(field("soldBooks"), field("unsoldBooks")).as("totalBooks"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Add(firestore.FieldOf("soldBooks"), firestore.FieldOf("unsoldBooks")).As("totalBooks"),
	)).
	Execute(ctx)

SUBTRACT

תחביר:

subtract[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

תיאור:

הפונקציה מחזירה את הערך של x - y.

לדוגמה:

x y subtract(x, y)
20 3 17
10.0 1 9.0
22.5 2.0 20.5
INT64.MAX -1 [error]
INT64.MIN 1 [error]
Node.js
const storeCredit = 7;
const result = await db.pipeline()
  .collection("books")
  .select(field("price").subtract(constant(storeCredit)).as("totalCost"))
  .execute();

אתר

const storeCredit = 7;
const result = await execute(db.pipeline()
  .collection("books")
  .select(field("price").subtract(constant(storeCredit)).as("totalCost"))
);
Swift
let storeCredit = 7
let result = try await db.pipeline()
  .collection("books")
  .select([Field("price").subtract(Constant(storeCredit)).as("totalCost")])
  .execute()
Kotlin
Android
val storeCredit = 7
val result = db.pipeline()
    .collection("books")
    .select(Expression.subtract(field("price"), storeCredit).alias("totalCost"))
    .execute()
‫Java
Android
int storeCredit = 7;
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.subtract(field("price"), storeCredit).alias("totalCost"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

store_credit = 7
result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("price").subtract(store_credit).as_("totalCost"))
    .execute()
)
Java
int storeCredit = 7;
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(subtract(field("price"), storeCredit).as("totalCost"))
        .execute()
        .get();
המשך
storeCredit := 7
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Subtract(firestore.FieldOf("price"), storeCredit).As("totalCost"),
	)).
	Execute(ctx)

MULTIPLY

תחביר:

multiply[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

תיאור:

הפונקציה מחזירה את הערך של x * y.

לדוגמה:

x y multiply(x, y)
20 3 60
‫10.0 1 ‫10.0
22.5 2.0 45.0
INT64.MAX 2 [error]
INT64.MIN 2 [error]
FLOAT64.MAX FLOAT64.MAX +inf
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("price").multiply(field("soldBooks")).as("revenue"))
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("price").multiply(field("soldBooks")).as("revenue"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("price").multiply(Field("soldBooks")).as("revenue")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.multiply(field("price"), field("soldBooks")).alias("revenue"))
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.multiply(field("price"), field("soldBooks")).alias("revenue"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("price").multiply(Field.of("soldBooks")).as_("revenue"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(multiply(field("price"), field("soldBooks")).as("revenue"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Multiply(firestore.FieldOf("price"), firestore.FieldOf("soldBooks")).As("revenue"),
	)).
	Execute(ctx)

DIVIDE

תחביר:

divide[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

תיאור:

הפונקציה מחזירה את הערך של x / y. התוצאה של חילוק מספרים שלמים מעוגלת כלפי מטה.

לדוגמה:

x y divide(x, y)
20 3 6
‫10.0 3 3.333...
22.5 2 11.25
10 0 [error]
1.0 0.0 +inf
-1.0 0.0 -inf
0.0 0.0 NaN
+inf +inf NaN
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("ratings").divide(field("soldBooks")).as("reviewRate"))
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("ratings").divide(field("soldBooks")).as("reviewRate"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("ratings").divide(Field("soldBooks")).as("reviewRate")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.divide(field("ratings"), field("soldBooks")).alias("reviewRate"))
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.divide(field("ratings"), field("soldBooks")).alias("reviewRate"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("ratings").divide(Field.of("soldBooks")).as_("reviewRate"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(divide(field("ratings"), field("soldBooks")).as("reviewRate"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Divide(firestore.FieldOf("ratings"), firestore.FieldOf("soldBooks")).As("reviewRate"),
	)).
	Execute(ctx)

MOD

תחביר:

mod[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

תיאור:

הפונקציה מחזירה את השארית של x / y.

  • הפונקציה מחזירה שגיאת error כש-y הוא אפס לסוגי מספרים שלמים (INT64).
  • הפונקציה מחזירה את הערך NaN כש-y הוא אפס לסוגי מספרים ממשיים (FLOAT64).

לדוגמה:

x y mod(x, y)
20 3 2
-10 3 -1
10 -3 1
-10 -3 -1
10 1 0
22.5 2 ‫0.5
22.5 0.0 NaN
25 0 [error]
Node.js
const displayCapacity = 1000;
const result = await db.pipeline()
  .collection("books")
  .select(field("unsoldBooks").mod(constant(displayCapacity)).as("warehousedBooks"))
  .execute();

אתר

const displayCapacity = 1000;
const result = await execute(db.pipeline()
  .collection("books")
  .select(field("unsoldBooks").mod(constant(displayCapacity)).as("warehousedBooks"))
);
Swift
let displayCapacity = 1000
let result = try await db.pipeline()
  .collection("books")
  .select([Field("unsoldBooks").mod(Constant(displayCapacity)).as("warehousedBooks")])
  .execute()
Kotlin
Android
val displayCapacity = 1000
val result = db.pipeline()
    .collection("books")
    .select(Expression.mod(field("unsoldBooks"), displayCapacity).alias("warehousedBooks"))
    .execute()
‫Java
Android
int displayCapacity = 1000;
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.mod(field("unsoldBooks"), displayCapacity).alias("warehousedBooks"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

display_capacity = 1000
result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("unsoldBooks").mod(display_capacity).as_("warehousedBooks"))
    .execute()
)
Java
int displayCapacity = 1000;
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(mod(field("unsoldBooks"), displayCapacity).as("warehousedBooks"))
        .execute()
        .get();
המשך
displayCapacity := 1000
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Mod(firestore.FieldOf("unsoldBooks"), displayCapacity).As("warehousedBooks"),
	)).
	Execute(ctx)

CEIL

תחביר:

ceil[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N

תיאור:

הפונקציה מחזירה את הערך השלם הקטן ביותר שלא קטן מ-number.

לדוגמה:

מספר ceil(number)
20 20
10 10
0 0
24L 24L
‫‎-0.4 ‫-0.0
0.4 1.0
22.5 23.0
NaN NaN
+inf +inf
-inf -inf
Node.js
const booksPerShelf = 100;
const result = await db.pipeline()
  .collection("books")
  .select(
    field("unsoldBooks").divide(constant(booksPerShelf)).ceil().as("requiredShelves")
  )
  .execute();

אתר

const booksPerShelf = 100;
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("unsoldBooks").divide(constant(booksPerShelf)).ceil().as("requiredShelves")
  )
);
Swift
let booksPerShelf = 100
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("unsoldBooks").divide(Constant(booksPerShelf)).ceil().as("requiredShelves")
  ])
  .execute()
Kotlin
Android
val booksPerShelf = 100
val result = db.pipeline()
    .collection("books")
    .select(
        Expression.divide(field("unsoldBooks"), booksPerShelf).ceil().alias("requiredShelves")
    )
    .execute()
‫Java
Android
int booksPerShelf = 100;
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        Expression.divide(field("unsoldBooks"), booksPerShelf).ceil().alias("requiredShelves")
    )
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

books_per_shelf = 100
result = (
    client.pipeline()
    .collection("books")
    .select(
        Field.of("unsoldBooks")
        .divide(books_per_shelf)
        .ceil()
        .as_("requiredShelves")
    )
    .execute()
)
Java
int booksPerShelf = 100;
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(ceil(divide(field("unsoldBooks"), booksPerShelf)).as("requiredShelves"))
        .execute()
        .get();
המשך
booksPerShelf := 100
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Ceil(firestore.Divide(firestore.FieldOf("unsoldBooks"), booksPerShelf)).As("requiredShelves"),
	)).
	Execute(ctx)

FLOOR

תחביר:

floor[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N

תיאור:

הפונקציה מחזירה את ערך המספר השלם הגדול ביותר שלא גדול מ-number.

לדוגמה:

מספר floor(number)
20 20
10 10
0 0
2147483648 2147483648
‫‎-0.4 -1.0
0.4 0.0
22.5 22.0
NaN NaN
+inf +inf
-inf -inf
Node.js
const result = await db.pipeline()
  .collection("books")
  .addFields(
    field("wordCount").divide(field("pages")).floor().as("wordsPerPage")
  )
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .addFields(
    field("wordCount").divide(field("pages")).floor().as("wordsPerPage")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .addFields([
    Field("wordCount").divide(Field("pages")).floor().as("wordsPerPage")
  ])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .addFields(
        Expression.divide(field("wordCount"), field("pages")).floor().alias("wordsPerPage")
    )
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .addFields(
        Expression.divide(field("wordCount"), field("pages")).floor().alias("wordsPerPage")
    )
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .add_fields(
        Field.of("wordCount").divide(Field.of("pages")).floor().as_("wordsPerPage")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .addFields(floor(divide(field("wordCount"), field("pages"))).as("wordsPerPage"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	AddFields(firestore.Selectables(
		firestore.Floor(firestore.Divide(firestore.FieldOf("wordCount"), firestore.FieldOf("pages"))).As("wordsPerPage"),
	)).
	Execute(ctx)

ROUND

תחביר:

round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N
round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N, places: INT64) -> N

תיאור:

מעגלת places ספרות של number. הפונקציה מעגלת ספרות מימין לנקודה העשרונית אם הערך של places חיובי, ומשמאל לנקודה העשרונית אם הערך שלילי.

  • אם מציינים רק את number, הפונקציה מעגלת למספר השלם הקרוב ביותר.
  • מעגלת את המספר כלפי מעלה או מטה, בהתאם לערך של הספרה שאחרי הנקודה העשרונית.
  • אם עיגול עם ערך places שלילי גורם לגלישה, נזרקת שגיאת error.

לדוגמה:

מספר מקומות round(number, places)
‫15.5 0 ‫16.0
-15.5 0 -16.0
15 1 15
15 0 15
15 -1 20
15 -2 0
15.48924 1 ‫15.5
‎231-1 -1 [error]
263-1L -1 [error]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("soldBooks").multiply(field("price")).round().as("partialRevenue"))
  .aggregate(field("partialRevenue").sum().as("totalRevenue"))
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("soldBooks").multiply(field("price")).round().as("partialRevenue"))
  .aggregate(field("partialRevenue").sum().as("totalRevenue"))
  );
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("soldBooks").multiply(Field("price")).round().as("partialRevenue")])
  .aggregate([Field("partialRevenue").sum().as("totalRevenue")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.multiply(field("soldBooks"), field("price")).round().alias("partialRevenue"))
    .aggregate(AggregateFunction.sum("partialRevenue").alias("totalRevenue"))
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.multiply(field("soldBooks"), field("price")).round().alias("partialRevenue"))
    .aggregate(AggregateFunction.sum("partialRevenue").alias("totalRevenue"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(
        Field.of("soldBooks")
        .multiply(Field.of("price"))
        .round()
        .as_("partialRevenue")
    )
    .aggregate(Field.of("partialRevenue").sum().as_("totalRevenue"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(round(multiply(field("soldBooks"), field("price"))).as("partialRevenue"))
        .aggregate(sum("partialRevenue").as("totalRevenue"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Round(firestore.Multiply(firestore.FieldOf("soldBooks"), firestore.FieldOf("price"))).As("partialRevenue"),
	)).
	Aggregate(firestore.Accumulators(
		firestore.Sum("partialRevenue").As("totalRevenue"),
	)).
	Execute(ctx)

TRUNC

תחביר:

trunc[N <: Number](number: N) -> N
trunc[N <: Number](number:  N, places: INT64) -> N

תיאור:

הפונקציה מקצרת את הערך של number למספר מסוים של ספרות אחרי הנקודה העשרונית places. הפונקציה חותכת ספרות מימין לנקודה העשרונית אם places חיובי, ומשמאל לנקודה העשרונית אם הוא שלילי.

  • אם מספקים רק את number, המערכת מעגלת את הערך למספר השלם הקרוב ביותר לכיוון אפס.
  • אם חיתוך התוצאות גורם לגלישה, מוצגת שגיאת error.

לדוגמה:

מספר מקומות trunc(number, places)
‫15.5 0 15.0
-15.5 0 -15.0
15 1 15
15 0 15
15 -1 10
15 -2 0
15.48924 1 15.4
-15.48924 2 ‫‎-15.48

POW

תחביר:

pow(base: FLOAT64, exponent: FLOAT64) -> FLOAT64

תיאור:

הפונקציה מחזירה את הערך base בחזקת exponent.

  • הפונקציה מחזירה שגיאה אם base <= 0 ו-exponent הם ערכים שליליים.

  • לכל exponent (כולל NaN), הערך של pow(1, exponent) הוא 1.

  • לכל base (כולל NaN), pow(base, 0) הוא 1.

לדוגמה:

בסיס מעריך pow(base, exponent)
2 3 ‫8.0
2 -3 0.125
+inf 0 1.0
1 +inf 1.0
NaN 0 1.0
1 NaN 1.0
NaN Numeric NaN
Numeric NaN NaN
-1 ‫0.5 [error]
0 -1 [error]
Node.js
const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
  .execute();

אתר

const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await execute(db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
);
Swift
let googleplex = CLLocation(latitude: 37.4221, longitude: 122.0853)
let result = try await db.pipeline()
  .collection("cities")
  .addFields([
    Field("lat").subtract(Constant(googleplex.coordinate.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    Field("lng").subtract(Constant(googleplex.coordinate.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  ])
  .select([
    Field("latitudeDifference").add(Field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  ])
  .execute()
Kotlin
Android
val googleplex = GeoPoint(37.4221, -122.0853)
val result = db.pipeline()
    .collection("cities")
    .addFields(
        field("lat").subtract(googleplex.latitude)
            .multiply(111) // km per degree
            .pow(2)
            .alias("latitudeDifference"),
        field("lng").subtract(googleplex.longitude)
            .multiply(111) // km per degree
            .pow(2)
            .alias("longitudeDifference")
    )
    .select(
        field("latitudeDifference").add(field("longitudeDifference")).sqrt()
            // Inaccurate for large distances or close to poles
            .alias("approximateDistanceToGoogle")
    )
    .execute()
‫Java
Android
GeoPoint googleplex = new GeoPoint(37.4221, -122.0853);
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("cities")
    .addFields(
        field("lat").subtract(googleplex.getLatitude())
            .multiply(111 /* km per degree */)
            .pow(2)
            .alias("latitudeDifference"),
        field("lng").subtract(googleplex.getLongitude())
            .multiply(111 /* km per degree */)
            .pow(2)
            .alias("longitudeDifference")
    )
    .select(
        field("latitudeDifference").add(field("longitudeDifference")).sqrt()
            // Inaccurate for large distances or close to poles
            .alias("approximateDistanceToGoogle")
    )
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

googleplexLat = 37.4221
googleplexLng = -122.0853
result = (
    client.pipeline()
    .collection("cities")
    .add_fields(
        Field.of("lat")
        .subtract(googleplexLat)
        .multiply(111)  # km per degree
        .pow(2)
        .as_("latitudeDifference"),
        Field.of("lng")
        .subtract(googleplexLng)
        .multiply(111)  # km per degree
        .pow(2)
        .as_("longitudeDifference"),
    )
    .select(
        Field.of("latitudeDifference")
        .add(Field.of("longitudeDifference"))
        .sqrt()
        # Inaccurate for large distances or close to poles
        .as_("approximateDistanceToGoogle")
    )
    .execute()
)
Java
double googleplexLat = 37.4221;
double googleplexLng = -122.0853;
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("cities")
        .addFields(
            pow(multiply(subtract(field("lat"), googleplexLat), 111), 2)
                .as("latitudeDifference"),
            pow(multiply(subtract(field("lng"), googleplexLng), 111), 2)
                .as("longitudeDifference"))
        .select(
            sqrt(add(field("latitudeDifference"), field("longitudeDifference")))
                // Inaccurate for large distances or close to poles
                .as("approximateDistanceToGoogle"))
        .execute()
        .get();
המשך
googleplexLat := 37.4221
googleplexLng := -122.0853
snapshot := client.Pipeline().
	Collection("cities").
	AddFields(firestore.Selectables(
		firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lat"), googleplexLat), 111), 2).As("latitudeDifference"),
		firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lng"), googleplexLng), 111), 2).As("longitudeDifference"),
	)).
	Select(firestore.Fields(
		firestore.Sqrt(firestore.Add(firestore.FieldOf("latitudeDifference"), firestore.FieldOf("longitudeDifference"))).
			// Inaccurate for large distances or close to poles
			As("approximateDistanceToGoogle"),
	)).
	Execute(ctx)

SQRT

תחביר:

sqrt[N <: FLOAT64 | DECIMAL128](number: N) -> N

תיאור:

מחזירה את השורש הריבועי של number.

  • הפונקציה מחזירה error אם number הוא שלילי.

לדוגמה:

מספר sqrt(number)
25 5.0
12.002 3.464...
0.0 0.0
NaN NaN
+inf +inf
-inf [error]
x < 0 [error]
Node.js
const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
  .execute();

אתר

const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await execute(db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
);
Swift
let googleplex = CLLocation(latitude: 37.4221, longitude: 122.0853)
let result = try await db.pipeline()
  .collection("cities")
  .addFields([
    Field("lat").subtract(Constant(googleplex.coordinate.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    Field("lng").subtract(Constant(googleplex.coordinate.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  ])
  .select([
    Field("latitudeDifference").add(Field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  ])
  .execute()
Kotlin
Android
val googleplex = GeoPoint(37.4221, -122.0853)
val result = db.pipeline()
    .collection("cities")
    .addFields(
        field("lat").subtract(googleplex.latitude)
            .multiply(111) // km per degree
            .pow(2)
            .alias("latitudeDifference"),
        field("lng").subtract(googleplex.longitude)
            .multiply(111) // km per degree
            .pow(2)
            .alias("longitudeDifference")
    )
    .select(
        field("latitudeDifference").add(field("longitudeDifference")).sqrt()
            // Inaccurate for large distances or close to poles
            .alias("approximateDistanceToGoogle")
    )
    .execute()
‫Java
Android
GeoPoint googleplex = new GeoPoint(37.4221, -122.0853);
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("cities")
    .addFields(
        field("lat").subtract(googleplex.getLatitude())
            .multiply(111 /* km per degree */)
            .pow(2)
            .alias("latitudeDifference"),
        field("lng").subtract(googleplex.getLongitude())
            .multiply(111 /* km per degree */)
            .pow(2)
            .alias("longitudeDifference")
    )
    .select(
        field("latitudeDifference").add(field("longitudeDifference")).sqrt()
            // Inaccurate for large distances or close to poles
            .alias("approximateDistanceToGoogle")
    )
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

googleplexLat = 37.4221
googleplexLng = -122.0853
result = (
    client.pipeline()
    .collection("cities")
    .add_fields(
        Field.of("lat")
        .subtract(googleplexLat)
        .multiply(111)  # km per degree
        .pow(2)
        .as_("latitudeDifference"),
        Field.of("lng")
        .subtract(googleplexLng)
        .multiply(111)  # km per degree
        .pow(2)
        .as_("longitudeDifference"),
    )
    .select(
        Field.of("latitudeDifference")
        .add(Field.of("longitudeDifference"))
        .sqrt()
        # Inaccurate for large distances or close to poles
        .as_("approximateDistanceToGoogle")
    )
    .execute()
)
Java
double googleplexLat = 37.4221;
double googleplexLng = -122.0853;
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("cities")
        .addFields(
            pow(multiply(subtract(field("lat"), googleplexLat), 111), 2)
                .as("latitudeDifference"),
            pow(multiply(subtract(field("lng"), googleplexLng), 111), 2)
                .as("longitudeDifference"))
        .select(
            sqrt(add(field("latitudeDifference"), field("longitudeDifference")))
                // Inaccurate for large distances or close to poles
                .as("approximateDistanceToGoogle"))
        .execute()
        .get();
המשך
googleplexLat := 37.4221
googleplexLng := -122.0853
snapshot := client.Pipeline().
	Collection("cities").
	AddFields(firestore.Selectables(
		firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lat"), googleplexLat), 111), 2).As("latitudeDifference"),
		firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lng"), googleplexLng), 111), 2).As("longitudeDifference"),
	)).
	Select(firestore.Fields(
		firestore.Sqrt(firestore.Add(firestore.FieldOf("latitudeDifference"), firestore.FieldOf("longitudeDifference"))).
			// Inaccurate for large distances or close to poles
			As("approximateDistanceToGoogle"),
	)).
	Execute(ctx)

EXP

תחביר:

exp(exponent: FLOAT64) -> FLOAT64

תיאור:

הפונקציה מחזירה את הערך של מספר אוילר בחזקת exponent, שנקרא גם פונקציית האקספוננט הטבעי.

לדוגמה:

מעריך exp(exponent)
0.0 1.0
10 e^10 (FLOAT64)
NaN NaN
+inf +inf
-inf 0
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").exp().as("expRating"))
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").exp().as("expRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").exp().as("expRating")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").exp().alias("expRating"))
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(field("rating").exp().alias("expRating"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("rating").exp().as_("expRating"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(exp(field("rating")).as("expRating"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Exp(firestore.FieldOf("rating")).As("expRating"),
	)).
	Execute(ctx)

LN

תחביר:

ln(number: FLOAT64) -> FLOAT64

תיאור:

הפונקציה מחזירה את הלוגריתם הטבעי של number. הפונקציה הזו שוות ערך ל-log(number).

לדוגמה:

מספר ln(number)
1 0.0
2L 0.693...
1.0 0.0
e (FLOAT64) 1.0
NaN NaN
-inf NaN
+inf +inf
x <= 0 [error]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").ln().as("lnRating"))
  .execute();

אתר

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").ln().as("lnRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").ln().as("lnRating")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").ln().alias("lnRating"))
    .execute()
‫Java
Android
Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(field("rating").ln().alias("lnRating"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("rating").ln().as_("lnRating"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(ln(field("rating")).as("lnRating"))
        .execute()
        .get();
המשך
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Ln(firestore.FieldOf("rating")).As("lnRating"),
	)).
	Execute(ctx)

LOG

תחביר:

log(number: FLOAT64, base: FLOAT64) -> FLOAT64
log(number: FLOAT64) -> FLOAT64

תיאור:

הפונקציה מחזירה את הלוגריתם של number בבסיס base.

  • אם מציינים רק את number, הפונקציה מחזירה את הלוגריתם של number בבסיס base (שווה ערך ל-ln(number)).

לדוגמה:

מספר בסיס log(number, base)
100 10 2.0
NaN Numeric NaN
Numeric NaN NaN
-inf Numeric NaN
Numeric. +inf NaN
number <= 0 Numeric [error]
Numeric base <= 0 [error]
Numeric 1.0 [error]

LOG10

תחביר:

log10(x: FLOAT64) -> FLOAT64

תיאור:

הפונקציה מחזירה את הלוגריתם של number בבסיס 10.

לדוגמה:

מספר log10(number)
100 2.0
NaN NaN
-inf NaN
+inf +inf
x <= 0 [error]

RAND

תחביר:

rand() -> FLOAT64

תיאור:

החזרת מספר נקודה צפה (floating-point) אקראי לכאורה, שנבחר באופן אחיד בין 0.0 (כולל) לבין 1.0 (לא כולל).

המאמרים הבאים