Skip to content

E. NQuery search by value's field

Fabian edited this page Jun 18, 2023 · 9 revisions

Index fields in your model

If you want to retrieve your entity other than with the KEY, you can index some fields and use these indexes to query your data

Player data class that contains a sub object PlayerStatistics

public class PlayerData extends NEntity<UUID> {

    @JsonProperty("statistics")
    private PlayerStatistics statistics;

    @JsonProperty("discordId")
    @Indexed
    private String discordId;
//...
}

PlayerStatistics

public class PlayerStatistics {

    @JsonProperty("kill")
    private int kill;

    @JsonProperty("death")
    private int death;

    @JsonProperty("score")
    @Indexed
    private int score;
//...
}

In this example, we want to index the discordIdof the player and his playerstat's score, which is embedded in another object. To do that, you just have to add a @Indexed annotation above the target field and NDatabase will index this field for you.

Use index to query your model

Once your fields are indexed properly, you can query your model using your Repository reference and a NQuery

Example 1 : Get a player by his discord id

repository.findOne(NQuery.predicate("$.discordId == 3432487284963298"));

Example 2 : Get best players, which have score >= 100 or a specific discord id

List<PlayerData > bestPlayers = repository.find(NQuery.predicate("$.statistics.score >= 100 || $.discordId == 3432487284963298"));

Your NQuery is actually a Boolean expression in the same fashion as in Java

  • start with $. to select the root object, and then concat the path of your desired field
  • apply operators (same as in Java) to these fields, you can use everything including > >= == < <= && || ( ) !=

Your predicate will be parsed into a boolean expression tree and then converted into a query of your target database type (either SQL query or MongoDB query)