【问题标题】:Check for duplicated in gae datastore检查 gae 数据存储中的重复项
【发布时间】:2016-12-28 00:51:34
【问题描述】:

我正在为我输入的每个添加命令创建一个实体,但我想知道如何检查数据存储区中的重复项?

    Entity entity = new Entity("Animal");
    entity.setProperty("nameOfAnimal",name_of_animal);

我要检查是否第二次输入了同名的动物,如何检查重复输入?

【问题讨论】:

    标签: google-app-engine google-cloud-datastore


    【解决方案1】:

    根据您要寻找的行为,您有多种选择。

    如果您使用nameOfAnimal 作为实体的名称,您可以在创建新实体之前尝试按键获取实体:

    Key animalKey = KeyFactory.createKey("Animal", "fox");
    Entity fox;
    try {
        fox = datastoreService.get(animalKey);
        // no exception thrown so fox already exists
        throw new RuntimeException("Animal already exists!");
    }
    catch(EntityNotFoundException e) {
        // no duplicates, so can create
        fox = new Entity(animalKey);
        fox.setNoise("unknown");
        datastoreService.put(fox);
    }
    

    如果您不使用 nameOfAnimal 作为键,您可以使用 Query("Animal") 而不是 get()(如 eluleci 的答案)。

    无论哪种方式,请注意那里存在潜在的竞争条件。如果您想让它安全,您需要将其包装在 transaction 中,否则您可能会发现两个线程竞争创建第一个 fox(例如),其中一个可能会覆盖另一个。

    【讨论】:

      【解决方案2】:

      您可以通过过滤“nameOfAnimal”属性来尝试获取实体并检查返回的结果。如果结果为空,则表示还没有实体。

      Filter propertyFilter =
        new FilterPredicate("nameOfAnimal", FilterOperator.EQUAL, name_of_animal);
      Query q = new Query("Animal").setFilter(propertyFilter);
      PreparedQuery pq = datastore.prepare(q);
      List<Animal> resultList = pq.asList(FetchOptions.Builder.withLimit(1));
      if(resultList.size() > 0) {
          // same name exists
      } else {
          // first entitiy with this name
      }
      

      代码未经测试,但这是主要思想。 Here is the documentation for property filters.

      【讨论】:

        【解决方案3】:

        可以将动物的名字作为实体的id,然后通过id获取该动物的名字是否存在。

        【讨论】:

          猜你喜欢
          • 2013-06-21
          • 2011-12-08
          • 1970-01-01
          • 1970-01-01
          • 2012-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多