2014-09-29 67 views
0

我想添加一個過濾器來檢查用戶可能輸入的重複值。我不確定我的查詢中哪裏出錯。篩選重複值。

我的查詢不進入循環檢查名稱是否已經存在。

我對google-could很新。如果有人能告訴我如何解決我的問題或者是否有更好的解決方案。

else if (commandEls[0].equals("add_director")) { 
     String name = commandEls[1]; 
     String gender = commandEls[2]; 
     String date_of_birth = commandEls[3]; 


     boolean duplicate = false; 
     //add a director record with the given fields to the datastore, don't forget to check for duplicates 

     Entity addDirectorEntity = new Entity("Director"); 

     // check if the entity already exits 
     // if !duplicate add, else "Already exisits" 

     Query directorExists = new Query("Movies"); 

     // Director Name is the primary key 
     directorExists.addFilter("directorName",Query.FilterOperator.EQUAL, name); 
     System.out.print(name); 
     PreparedQuery preparedDirectorQuery = datastore.prepare(directorExists); 

     System.out.print("outside");  
     for(Entity directorResult : preparedDirectorQuery.asIterable()){ 
      // result already exists in the database 
      String dName = (String) directorResult.getProperty(name); 
      System.out.print(dName); 
      System.out.print("finish"); 
      duplicate = true; 
     } 

     if(!duplicate){ 
      addDirectorEntity.setProperty("directorName",name); 
      addDirectorEntity.setProperty("directorGender",gender); 
      addDirectorEntity.setProperty("directorDOB",date_of_birth); 

      try{ 
       datastore.put(addDirectorEntity); 
       results = "Command executed successfully!"; 
      } 
      catch(Exception e){ 
       results = "Error"; 
      } 
     } 

     else { 
      results = "Director already exists!"; 
     } 

    } 

回答

0

非祖先查詢(像在你的例子)是最終一致,所以他們不能可靠地檢測重複的屬性值。祖先查詢是完全一致的,但它們需要使用實體組來構造數據,這是以寫入吞吐量爲代價的。

如果您示例中的directorName屬性確實是唯一的,那麼您的Director實體的use it as the name in the key即可。然後,當你插入一個新的實體時,你可以首先檢查它是否已經存在(在一個事務中)。

數據存儲中沒有通用的內置方法來確保屬性值的唯一性。這個相關的feature request包含用於逼近唯一性約束的一些可能的策略的討論。

我還建議您閱讀數據存儲中的queriesconsistency

0

這是一個有效的事情,但我想通了我的問題。 我正在爲導演製作一個實體,因爲這應該是電影。