Questions tagged [select-n-plus-1]

Use this tag for the ORM problem known as select N+1 queries.

Filter by
Sorted by
Tagged with
0 votes
0 answers
10 views

Is it possible to encounter n+1 problem in NoSQL given the data model is designed properly?

I think it is impossible to encounter such a problem. Because if the data model is designed properly, we keep related data together in NoSQL. Is it possible?
0 votes
1 answer
46 views

Custom logger for rails prosopite gem

How to configure prosopite gem in rails for custom logger file. I need to separate file for specs and API scan details. for example: prosopite_api.log file for API scan details. prosopite_specs.log ...
  • 153
0 votes
0 answers
43 views

N+1 problem for non primary key relation and eager fetch type (random n+1)

I have a problem with N+1 for non primary key relation and eager fetch type if there nested fetch in query Entity(C) has relationship with other entity(B) by non primary field, which has eager fetch ...
3 votes
2 answers
176 views

"Traditional" one-to-many Query with RavenDB

I know the include-feature of RavenDB. It allows me to fetch a referenced document right away in one roundtrip to the database. But my problem is: The document i fetch in the first place is not ...
  • 1,616
0 votes
0 answers
183 views

How to optimise and speed up .find and .build on large number of records?

I have a form that accepts a true/false value for every hour of the day for 3 weeks (total of 504 1 hour time slots). I am trying to reduce the time it takes for this page to load (currently 3 seconds ...
  • 37.4k
0 votes
2 answers
511 views

LEFT JOIN FETCH not solving n+1 issue

I would like to ask about solution for N+1 issue. I have Account table and Account_role table with 1:M relationship. I try the join fetch method by using LEFT JOIN FETCH in @Query but does not work. ...
0 votes
1 answer
5 views

Look for an attribute in an eager loded subsection of a subsection, without causing a SQL call?

I have a set of models like below (the actual setup displayed here is a simplified mockup): Blog has_many :posts Post has_many :comments # contributor_id is a part of Post Contributor # having ...
  • 2,251
0 votes
2 answers
37 views

Smart way of not getting N+1 while querying has_many relationship in Rails?

I have a Movie model and a MovieStream model. The relation is Movie has_many MediaType (and MediaType belongs_to Movie). MediaType has two attribues "url_broken" (true/false) and "dvd&...
  • 2,251
0 votes
1 answer
177 views

How to correctly represent a "warehouse" in django - n+1 problems

I'm learning Django. I am trying to make an app for managin a warehouse that's composed by simple elements: Involved models are transaction, items, warehouses and homes. models.py: class Home(Model): ...
  • 131
0 votes
1 answer
168 views

Django N+1 problem with serpy.MethodField

I use nplusone to detect N+1 queries. I have a serpy serializer that serializes Order instances. An Order has a cart consisting of OrderComponent instances, as shown below. Code simplified: class ...
4 votes
1 answer
560 views

Is it possible to count the number of SQL queries with Flask / SQLAlchemy / Pytest / SQLite?

I have a Flask project which uses SQLAlchemy and a database. For testing, I replace the database by an SQLite database. Now I would like to run some of the views and test for the number of queries ...
0 votes
1 answer
28 views

Include a left joined has_many association with condition

There is an association query I seem to be unable to do without triggering a N+1 query. Suppose I host Parties. I have many Friends, and each time a friend comes to a party, they create a Presence. ...
2 votes
2 answers
886 views

How to avoid N + 1 queries with self-referential table in Rails

How to I correctly use includes to avoid N + 1 queries in this situation: I have a set of categories that can be nested (i.e., they form a tree). For example: Teaching Course 1 Office Hours ...
  • 6,026
2 votes
1 answer
693 views

Doctrine adds extra queries during hydration causing n+1 problem with "normal" one to one and self-referenced relations

News are related to each other using one-to-many self-referencing approach (one news is parent and can have many children). What's more each News has got normal (non self-referenced) one to one ...
  • 126
2 votes
1 answer
380 views

Detecting N+1 query issues during testing with JPA and Hibernate

We're using Hypersistence Utils, which is a great tool, but we're facing a challenge regarding Session cache, as mentioned in another question; it can't be disabled. So, the following test fails ...
3 votes
3 answers
205 views

How to add information from the DB to an existing array of objects?

I have an array in the following format; // echo '<pre>' . var_export($this->viewableFields, true) . '</pre>'; array ( 0 => (object) array( 'formId' => '4', '...
  • 2,719
0 votes
1 answer
473 views

Rails: This SQL query was called multiple times and my be opthimised for eager loading

I am seeing the above issue in rails simple activerecord query where(email:email).first_or_create! find_or_create_by!(phone_number: phone_number) Both these queries are not part of any other query ...
  • 333
3 votes
1 answer
1k views

How to fix "Potential unnecessary eager load detected on `LogEntry.user`"

I'm creating a new Django 2.2 project with plugin nplusone(https://github.com/jmcarp/nplusone). When I try to go on /admin URL I get a next error “Potential unnecessary eager load detected on LogEntry....
2 votes
1 answer
908 views

Hibernate performs N+1 selects instead of 1 query when using the Query Cache

I'm stuck with a problem, I feel really lost and don't know what to do. I use query cache + second-level cache and I want to cache results for 10 seconds properly. So here is my ehcache.xml: <...
0 votes
1 answer
75 views

N+1 issue for custom method in rails

in my rails app I have a User model with a method called price_tier: def price_tier Spree::PriceTier.by_code[read_attribute(:price_tier)] end However, when I have a collection of @users and call ...
  • 3,652
1 vote
1 answer
290 views

How to avoid attachment N+1

Given class User < ApplicationRecord has_one_attached :avatar def avatar_path Rails.application.routes.url_helpers.rails_blob_path avatar, ...
  • 35.1k
0 votes
1 answer
168 views

Avoiding n+1 query on rails STI with different relationships

So let's say I have the following models: class Building < ActiveRecord::Base has_many :rooms has_many :training_rooms, class_name: 'TrainginRoom', source: rooms has_many :computers, through:...
  • 17.3k
8 votes
3 answers
6k views

JPA @OneToOne select lists with N+1 queries

I'm actually trying to use JPA @OneToOne annotation to link a Child entity to its Parent. It's working well, except the fact that when getting a list of Childs, the JPA engine (Hibernate in this case)...
2 votes
1 answer
202 views

Rails: Optimize query N+1 with same table one_to_many and scope conditions

Here's a challenge I'm facing, using Rails 5 (I use Skylight service that reports N+1 queries, and their recommended solution is here, but it's not enough in my case). I have a table nodes and a ...
  • 1,214
2 votes
1 answer
398 views

How to do nested SQLlite queries efficiently

I have a database of (Soccer) games, containing child tables of periods (e.g. first and second half), events (e.g. a goal, a caution), and locations (where you were prior to and during the game). To ...
  • 713
0 votes
0 answers
729 views

How to fix N+1 rails

I have a specific inlcudes in my controller for contentType model. I need to catch all of content suites in this page with preloading. This is a fetch method for it: def fetch_content_suites ...
19 votes
2 answers
15k views

EF Core nested Linq select results in N + 1 SQL queries

I have a data model where a 'Top' object has between 0 and N 'Sub' objects. In SQL this is achieved with a foreign key dbo.Sub.TopId. var query = context.Top //.Include(t => t.Sub) Doesn't ...
  • 1,933
0 votes
1 answer
52 views

Session.Get loads with N+1 even when lazy=false

I have entities like these: public class User { public virtual int Id { get; set;} public virtual Iesi.Collections.Generic.ISet<Character> Characters { get; set; } } public class ...
  • 2,934
2 votes
1 answer
2k views

SQLAlchemy Efficient Subquery for Latest Value

The current value of an Entity's status attribute can queried as the latest entry in a EntityHistory table for that entity, i.e. Entities (id) <- EntityHistory (timestamp, entity_id, value) How ...
4 votes
3 answers
2k views

how to automatically identify n+1 queries in a django app?

Is there any tool, plugin or technique that I can use to help identify n+1 queries on a Django application? There is a gem called bullet for Rails that identifies n+1 queries and logs or pops up ...
0 votes
1 answer
141 views

solving select n + 1 automatically

This provides a simple example of select n + 1 problem in ORM in pht, but the idea should be the same in other ORM of other languages. A typical solution is to use eager loading to reduce it to 1 ...
2 votes
0 answers
310 views

N+1 issue with rails partial

I have a Booking model , associated with Availability > Facility > Venue I have a page in my view which renders all bookings for a given venue and it's causing a huge N+1 query. Controller ...
  • 5,439
1 vote
1 answer
63 views

Hibernate querying the entity after fetching its collection

We have the following 2 classes public class StagingConcept implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "sequence") @SequenceGenerator(name =...
1 vote
1 answer
2k views

Rails 4, ActiveRecord SQL subqueries

A :parent has_many :children and I am trying to retrieve the age of the oldest child for a parent as an attribute on the parent. I'm open to any solution that accomplishes that efficiently. The ...
  • 4,239
0 votes
0 answers
59 views

How to "group resolve" a property for a list of objects?

I have a list of some objects, which I populate from a database query result. List<Competition> myList; // fetched from DB If I need to access a property of one/several of the object in this ...
8 votes
4 answers
7k views

Hibernate creating N+1 queries for @ManyToOne JPA annotated property

I have these classes: @Entity public class Invoice implements Serializable { @Id @Basic(optional = false) private Integer number; private BigDecimal value; //Getters and setters ...
6 votes
4 answers
634 views

Why is the n+1 selects pattern slow?

I'm rather inexperienced with databases and have just read about the "n+1 selects issue". My follow-up question: Assuming the database resides on the same machine as my program, is cached in RAM and ...
  • 12.3k
1 vote
1 answer
184 views

n+1 query not working

In the below code I expect the n+1 query problem to occur, but it's not happening. User.java: import java.util.*; public class User { private long userId; private String firstName; ...
3 votes
1 answer
1k views

N+1 issue on bidirectional one-to-one with Jpa and Hibernate

The query being executed is: from PurchaseOrder o join fetch o.basket where o.statusE in (:statuses) Mapping in PurchaseOrder: @OneToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY, optional = ...
  • 1,776
1 vote
1 answer
3k views

Annotation @BatchSize not working

I have 3 JPA classes an Account that includes a single Address which has a City Object public class Account implements java.io.Serializable { // Fields private Address address; //Setters and ...
  • 193
2 votes
2 answers
815 views

Eager loading an optional one-to-one with NHibernate

Consider the following simplified domain: public class Movie { public virtual int Id { get; set; } public virtual MovieDetail MovieDetail { get; set; } } public class MovieDetail { ...
  • 13.6k
0 votes
1 answer
288 views

N+1 in rails relations with active records?

I have four models Group Reports Comments user Group => has_many => Reports Report => has_many => Comments Comment => Belongs_to => User When i want to show a group I do something like <%= @...
  • 1,852
2 votes
2 answers
1k views

Prevent "n+1 selects" with JPA/Hibernate constructor expression?

I have two entities, Item and Data, and a DTO class ItemData. ItemData consists of Item and Data and has no JPA mapping. To retreive a list of populated ItemDatas, I use a constructor expression in ...
  • 10.4k
2 votes
1 answer
695 views

Why SELECT N + 1 with no foreign keys and LINQ?

I have a database that unfortunately have no real foreign keys (I plan to add this later, but prefer not to do it right now to make migration easier). I have manually written domain objects that map ...
4 votes
1 answer
263 views

Why would identical NHibernate queries run an order of magnitude slower in a WinForm project than an MSTest unit test?

I have an app that is run as a service in production, but we do some manual testing with a simple GUI - practically nothing going on in it, it's just a wrapper with a textbox for input. I recently ...
1 vote
1 answer
794 views

NHibernate Select N+1 and Recursive

I've got a couple of data classes: public class RecordGroup { public virtual DataRecord RootDataRecord; } public class DataRecord { public virtual string Name { get; set; } public ...
19 votes
2 answers
1k views

How can you avoid NHibernate N+1 with composite key

EDIT I remade an entire project for this one problem. And thus, I remade the question. I want to be able to efficiently avoid N+1 and Cartesian joins joining together a 4 level deep entity with a ...
  • 2,364
1 vote
1 answer
286 views

I can't avois this select N+1

I have this mapping ( it comes from adventureworks since I used it in a demo app for an automatic paging collection ) ModelMapper mapper = new ModelMapper(new SimpleModelInspector()); ...
5 votes
3 answers
491 views

Which is the fastest performing way to avoid n+1 issues and why?

I'm looking to add some utility methods to help avoid a lot of n+1 issues in a legacy application. The common pattern is this: select a.* /* over 10 columns */ from [table-A] a where /* something */ ...
  • 148k
15 votes
2 answers
19k views

Hibernate Subselect vs Batch Fetching

Hibernate provides (at least) two options for getting around the N+1 query problem. The one is setting the FetchMode to Subselect, which generates a select with a IN-clause and a subselect within this ...
  • 2,922