Reputation: 465
I need to check if a field contains specific String
, and if it does - delete the entire row by id.
This code doesn't working:
Query<Bet> query = ofy().load().type(Movie.class);
for (Movie m : query) {
List<String> list = m.getActors();
String search = "Brad Pitt";
for (String str : list) {
if (str.trim().contains(search)) {
ofy().delete().type(Movie.class).id(m.getId()).now();
}
}
}
Upvotes: -1
Views: 617
Reputation: 5227
In this case (deleting all movies with Brad Pitt in it as an actor) you could delete the entity like this:
Query<Movie> query = ofy().load().type(User.class);
for (Movie m : query) {
List<String> list = m.getActors();
String search = "Brad Pitt";
for (String str : list) {
if (str.trim().contains(search)) {
ofy().delete().entity(m).now();
}
}
}
Not that i delete with delete().entity(...)
. Another option would be to delete by key like so delete().key(Key.create(Movie.class, idToRemove)
. The former does something quite similar but since you have the whole entity you don't need to complicate things. Also if you delete with entity(...)
it will work when the entity has a @Parent
whereas if you delete by key you'd have to additionally specify the ancestor in Key.create(ancestorKey, Movie.class, idToRemove)
.
I usually do multiple deletes like this:
Query<Movie> query = ofy().load().type(User.class);
List<Movie> toDelete = new ArrayList<>();
for (Movie m : query) {
List<String> list = m.getActors();
String search = "Brad Pitt";
for (String str : list) {
if (str.trim().contains(search)) {
toDelete.add(m);
}
}
}
ofy().delete().entities(toDelete).now();
Performing database operations in a loop is bad style and should be avoided if possible.
One more thing:
If you must delete an entity by id the line would look like this:
ofy().delete().type(Movie.class).id(idToDelete);
However, as i hinted at before, if your Movie
class has a parent this will not work because you must always specify the whole key, thus with ancestor the line would look like this:
Key<MyParentClass> parent = Key.create(MyParentClass.class, myParentId);
ofy().delete().type(Movie.class).parent(parent).id(idToDelete);
which is equivalent to
ofy().delete().key(Key.create(Key.create(MyParentClass.class, myParentId), Movie.class, idToDelete));
Upvotes: 1