Repository navigation
Description
Dear Postgres team,
I created a repo with a minimal example to reproduce our issue with ILike. See the readme in the repo for a detailed description.
In short:
We have array columns (by intention) to store e.g. a user's competencies, topics etc. Now, users should be able to search across these columns, also with partial wording. Let's say, user A stores ["Artificial Intelligence", "Big Data", "Robotics"]. Then, any user should be able to find this entry by search for "intelli".
Regarding to the "Array Type Mapping" documentation, we assumed that we could archive this by:
.Where(n => n.Topics.Any(s => EF.Functions.ILike(s, $"%{searchTerm1}%")))
It throws an NullReferenceException:
System.NullReferenceException: Object reference not set to an instance of an object.
at Npgsql.EntityFrameworkCore.PostgreSQL.Query.NpgsqlSqlExpressionFactory.ApplyTypeMappingsOnItemAndArray(SqlExpression itemExpression, SqlExpression arrayExpression)
at Npgsql.EntityFrameworkCore.PostgreSQL.Query.NpgsqlSqlExpressionFactory.ApplyTypeMappingOnAny(PostgresAnyExpression postgresAnyExpression)
at Npgsql.EntityFrameworkCore.PostgreSQL.Query.NpgsqlSqlExpressionFactory.ApplyTypeMapping(SqlExpression sqlExpression, RelationalTypeMapping typeMapping)
at Microsoft.EntityFrameworkCore.Query.SqlExpressionFactory.ApplyDefaultTypeMapping(SqlExpression sqlExpression)
at Npgsql.EntityFrameworkCore.PostgreSQL.Query.NpgsqlSqlExpressionFactory.Any(SqlExpression item, SqlExpression array, PostgresAnyOperatorType operatorType)
at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlSqlTranslatingExpressionVisitor.VisitArrayMethodCall(MethodInfo method, ReadOnlyCollection`1 arguments)
at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCall)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.Translate(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateExpression(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateLambdaExpression(ShapedQueryExpression shapedQueryExpression, LambdaExpressi
on lambdaExpression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at BugILikePostgres.Program.Main(String[] args) in C:\_Data\Repositories\BugILikePostgres\BugILikePostgres\Program.cs:line 73
When I exchanged the matchExpress with the pattern parameter, it "works" . But obviously, we cannot use pattern anymore in such a case. But this exchanging shows, that there is no null field.
Is this a bug, or have we misunderstood the documentation? 🙂
For reference: I mentioned this issue first on issue #395.
Activity
roji commentedon Nov 2, 2020
PostgreSQL has indeed has LIKE ANY (see the docs), and Npgsql does translate it (see the Npgsql translation docs). However, the array in this construct needs to contain the LIKE patterns, not the values to be matched against a single pattern.
In other words, I'm asking what SQL you would like to see for your LINQ expression above? It's probably possible to translate this via unnest in a subquery, though that wouldn't be efficient so I'm not sure it's a good idea.
(Regardless, there is a minor bug which causes this to throw a NullReferenceException instead of a regular translation failure. I'll fix that).
roji commentedon Nov 2, 2020
For now, I'm submitting a PR to fix the NRE (and trigger a translation failure instead). If this conversation leads to an actual translation of the expression above, I can reopen.
Fixes around array.Any translation
Fixes around array.Any translation (#1556)
SommerEngineering commentedon Nov 4, 2020
Thanks @roji 🙂
For everyone who is interested in this use case and finds this issue via search engine:
I added a second scenario, where the text gets stored in an additional table
Topics(replacing thestring[]column). Then, the tableUserscan assign related topic ids to any user by using aint[]column. When I pull the matching topic ids to the C# side, I could finally useWhere(n => n.Topics.Any(i => matchingTopicIds.Contains(i))), which works fine (see attempt 5).In attempt 6, though, I tried the same but executing the entire query on the db side, which does not work.
Pulling the ids to the C# side may seems bad. But this is not true, it depends on the application. If your users have a list of tags or topics in the frontend anyway and select the appropriate ones there, you already have the matching ids. Or if you run the search function for matching tags in the frontend anyway, you also have the matching ids. Therefore this solution is quite suitable.
JohnC-Ditno commentedon Nov 24, 2020
As an example SQL statement in Postgres I'm able to achieve the required partial (LIKE) search on an array type column using unnest() in a subquery:
SELECT *
FROM myTable
WHERE EXISTS (
SELECT -- can be empty
FROM unnest(myStringArrayColumn) elem
WHERE elem LIKE '%someInput%'
);
I don't imagine this would be supported in efcore.pg though?
The only other workaround I can see would be to normalize the array columns into a separate table as mentioned by @SommerEngineering
roji commentedon Nov 24, 2020
@JohnDitno this is what I was referring to in #1554 (comment).
It should be possible to implement this in EFCore.PG - though not trivial. However, the main point is that as I wrote above, I don't think this can use indexes and would therefore have poor performance.
Note that you can easily wrap something like this in a PG function and execute that.
JohnC-Ditno commentedon Nov 24, 2020
@roji from further reading online I don't believe unnest can use indexes so your right performance is likely to be poor.
I did find an extension called parray_gin (https://github.com/theirix/parray_gin/) which seems to provide GIN index and operator support for arrays with partial match but this is likely to fall outside of EFCore.PG support.
I think to best option to support this use case would be to normalise the array column into a separate table so LIKE operations can leverage the indexing for better performance
roji commentedon Nov 24, 2020
Thanks for looking into this further.
FWIW I'm open to any translation that makes sense - including those which are complicated and/or require extensions (although exotic extensions are maybe a bit too much). What I'm wary of, is implementing translations which definitely yield bad performance in most/all cases where they're used, and where this isn't very obvious to the person writing the LINQ query.