Conditional updates & deletes通过提交任何爪哇,斯卡拉,科特林或任何本地人JVM代码/功能。 有没有查询语言。
仅仅是JVM函数/代码,我们可以
- Be more expressive in writing our query logic as we are not restricted by rules of a query language.
- Use external Java libraries within our queries like Joda-Time for time management, Jackson or Circe for JSON parsing etc.
- Write test-cases using familiar testing libraries like JUnit, kotlin.test, ScalaTest etc.
- Type-safe - catch errors during compile time.
- Fast - No runtime parsing & compiling performance cost. See these benchmarks that show 482,000+ writes per second. Function updates follow the same write path as any basic write and do not incur any extra cost.
Example
一个简单的示例可以创建一个Map<串, 双>那存储产品名称作为关键和价钱作为价值。 您可以使用自定义类(产品.java值),但为了简单起见串和双用来。
更新逻辑:如果产品的有效期限还不到2天,请给予50%的折扣!
//Our function that implements the update logic.
//You can also use PureFunction.OnValue or PureFunction.OnKey.
PureFunction.OnKeyValue<String, Double, Return.Map<Double>> discount =
(String product, Double price, Optional<Deadline> deadline) -> {
//if there are less than 2 days to expiry then apply discount.
if (deadline.isPresent() && deadline.get().timeLeft().minusDays(2).isNegative()) {
double discountedPrice = price * 0.50; //50% discount.
if (discountedPrice <= 10) { //If the price is below $10
//return Return.expire(Duration.ZERO); //expire it
return Return.remove(); //or remove the product
return Return.update(discountedPrice); //else update with the discounted price
return Return.nothing(); //else do nothing.
//create our map with functions enabled.
Map<String, Double, PureFunction<String, Double, Return.Map<Double>>> products =
MapConfig.functionsOn(stringSerializer(), doubleSerializer())
.registerFunction(discount) //register the discount function
//insert two products that expire after a day.
products.put("MacBook Pro", 2799.00, Duration.ofDays(1));
products.put("Tesla", 69275.0, Duration.ofDays(1));
//apply the discount function.
products.applyFunction("MacBook Pro", "Tesla", discount);
我们可以使用以下命令打印地图的内容
products.stream().forEach(System.out::println);
在应用折扣之前,将打印
KeyVal(MacBook Pro,2799.0) KeyVal(Tesla, 69275.0)
应用折扣后打印
KeyVal(MacBook Pro,1399.5) KeyVal(Tesla, 34637.5)
See the above example on GitHub - DiscountApp.java.
What is function ID?
每纯功能类型也实现字串编号存储在数据库中的值。 目前ID默认为this.getClass()。getName(); which can be overrIDden by your function.
Note & TODOs
- 该函数本身未序列化。 只有功能的ID被序列化并存储在数据库中。 TODO-可序列化的功能。.mightContainFunction可用于检查功能是否正在使用。 TODO-自动功能删除。TODO-较强的类型注册和申请功能。
Useful links
from: https://dev.to//simerplaha/functions-as-queries-swaydb-538n