├── nuget-icon.png ├── README.md ├── ElasticSearchQuery ├── nuget-icon.png ├── Helpers │ ├── ExpressionHelper.cs │ └── TypeSystem.cs ├── Extensions │ └── StringExtensions.cs ├── ElasticSearchQueryFactory.cs ├── QueryProvider.cs ├── ElasticSearchQuery.csproj ├── ElasticQuery.cs ├── ElasticQueryMapper.cs ├── ElasticQueryProvider.cs └── QueryTranslator.cs ├── ElasticsearchQuery └── Extensions │ ├── IQueryableExtensions.cs │ └── ObjectExtensions.cs ├── ElasticSearchQuery.Tests ├── ElasticSearchQuery.Tests.csproj └── QueryTests.cs ├── LICENSE ├── ElasticSearchQuery.sln ├── .gitattributes ├── .github └── workflows │ └── codeql-analysis.yml └── .gitignore /nuget-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leonardosimoura/ElasticsearchQuery/HEAD/nuget-icon.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ElasticsearchQuery 2 | 3 | Moved to https://github.com/ElasticsearchQuery/ElasticsearchQuery 4 | -------------------------------------------------------------------------------- /ElasticSearchQuery/nuget-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leonardosimoura/ElasticsearchQuery/HEAD/ElasticSearchQuery/nuget-icon.png -------------------------------------------------------------------------------- /ElasticsearchQuery/Extensions/IQueryableExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | 7 | namespace ElasticsearchQuery.Extensions 8 | { 9 | public static class IQueryableExtensions 10 | { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ElasticSearchQuery/Helpers/ExpressionHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Text; 5 | 6 | namespace ElasticsearchQuery.Helpers 7 | { 8 | internal static class ExpressionHelper 9 | { 10 | internal static Expression StripQuotes(Expression e) 11 | { 12 | while (e.NodeType == ExpressionType.Quote) 13 | { 14 | e = ((UnaryExpression)e).Operand; 15 | } 16 | return e; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ElasticsearchQuery/Extensions/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Text; 5 | 6 | namespace ElasticsearchQuery.Extensions 7 | { 8 | public static class ObjectExtensions 9 | { 10 | public static bool MultiMatch(this TObj obj, string query, params Expression>[] fields) 11 | { 12 | return true; 13 | } 14 | 15 | public static bool Exists(this TObj obj, Expression> field) 16 | { 17 | return true; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ElasticSearchQuery/Extensions/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace ElasticsearchQuery.Extensions 6 | { 7 | public static class StringExtensions 8 | { 9 | internal static string ToCamelCase(this string str) 10 | { 11 | if (string.IsNullOrWhiteSpace(str)) 12 | return str; 13 | 14 | return str.Trim()[0].ToString().ToLower() + str.Trim().Substring(1); 15 | } 16 | 17 | public static bool MatchPhrase(this string str, string exp) 18 | { 19 | return true; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ElasticSearchQuery/ElasticSearchQueryFactory.cs: -------------------------------------------------------------------------------- 1 | using Nest; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace ElasticsearchQuery 8 | { 9 | public class ElasticSearchQueryFactory 10 | { 11 | [Obsolete("This method will be removed in version 1.0. Use the ElasticSearchQueryFactory.CreateQuery.")] 12 | public static IQueryable GetQuery(IElasticClient client) 13 | { 14 | var provider = new ElasticQueryProvider(client); 15 | return new ElasticQuery(provider); 16 | } 17 | 18 | public static IQueryable CreateQuery(IElasticClient client) 19 | { 20 | var provider = new ElasticQueryProvider(client); 21 | return new ElasticQuery(provider); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ElasticSearchQuery.Tests/ElasticSearchQuery.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Leonardo Silvio de Moura 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ElasticSearchQuery/QueryProvider.cs: -------------------------------------------------------------------------------- 1 | using ElasticsearchQuery.Helpers; 2 | using System; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | 7 | namespace ElasticsearchQuery 8 | { 9 | internal abstract class QueryProvider : IQueryProvider 10 | { 11 | protected QueryProvider() 12 | { 13 | 14 | } 15 | 16 | IQueryable IQueryProvider.CreateQuery(Expression expression) 17 | { 18 | return new ElasticQuery(this, expression); 19 | } 20 | 21 | IQueryable IQueryProvider.CreateQuery(Expression expression) 22 | { 23 | Type elementType = TypeSystem.GetElementType(expression.Type); 24 | 25 | try 26 | { 27 | return (IQueryable)Activator.CreateInstance(typeof(ElasticQuery<>).MakeGenericType(elementType), new object[] { this, expression }); 28 | } 29 | catch (TargetInvocationException tie) 30 | { 31 | throw tie.InnerException; 32 | } 33 | } 34 | 35 | S IQueryProvider.Execute(Expression expression) 36 | { 37 | return (S)this.Execute(expression); 38 | } 39 | 40 | object IQueryProvider.Execute(Expression expression) 41 | { 42 | return this.Execute(expression); 43 | } 44 | 45 | public abstract object Execute(Expression expression); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ElasticSearchQuery/ElasticSearchQuery.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | See https://github.com/leonardosimoura/ElasticSearchQuery 6 | https://github.com/leonardosimoura/ElasticSearchQuery/blob/master/nuget-icon.png 7 | https://github.com/leonardosimoura/ElasticSearchQuery/blob/master/LICENSE 8 | https://github.com/leonardosimoura/ElasticSearchQuery 9 | https://github.com/leonardosimoura/ElasticSearchQuery.git 10 | git 11 | ElasticsearchQuery 12 | Simple IQueryable implementation for Elasticsearch 13 | Leonardo Silvio de Moura 14 | 0.1.9 15 | true 16 | true 17 | true 18 | Elasticsearch Elastic Nest ElasticsearchQuery Query 19 | 0.1.9.0 20 | 0.1.9.0 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /ElasticSearchQuery.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29418.71 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ElasticsearchQuery", "ElasticSearchQuery\ElasticsearchQuery.csproj", "{2B5E61F2-E9E4-4CA7-BB25-0B9271A66666}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ElasticsearchQuery.Tests", "ElasticSearchQuery.Tests\ElasticsearchQuery.Tests.csproj", "{DF20074F-1732-4A5B-9F10-9C7E51A2E85D}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {2B5E61F2-E9E4-4CA7-BB25-0B9271A66666}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {2B5E61F2-E9E4-4CA7-BB25-0B9271A66666}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {2B5E61F2-E9E4-4CA7-BB25-0B9271A66666}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {2B5E61F2-E9E4-4CA7-BB25-0B9271A66666}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {DF20074F-1732-4A5B-9F10-9C7E51A2E85D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {DF20074F-1732-4A5B-9F10-9C7E51A2E85D}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {DF20074F-1732-4A5B-9F10-9C7E51A2E85D}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {DF20074F-1732-4A5B-9F10-9C7E51A2E85D}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {D4572C46-CB46-495A-9CB8-0FDBA597ADF7} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /ElasticSearchQuery/ElasticQuery.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Text; 7 | 8 | namespace ElasticsearchQuery 9 | { 10 | internal class ElasticQuery : IQueryable, IQueryable, IEnumerable, IEnumerable, IOrderedQueryable, IOrderedQueryable 11 | { 12 | IQueryProvider provider; 13 | Expression expression; 14 | 15 | public ElasticQuery(IQueryProvider provider) 16 | { 17 | if (provider == null) 18 | throw new ArgumentNullException("provider"); 19 | 20 | 21 | this.provider = provider; 22 | 23 | this.expression = Expression.Constant(this); 24 | } 25 | 26 | public ElasticQuery(IQueryProvider provider, Expression expression) 27 | { 28 | if (provider == null) 29 | throw new ArgumentNullException("provider"); 30 | 31 | 32 | if (expression == null) 33 | throw new ArgumentNullException("expression"); 34 | 35 | if (!typeof(IQueryable).IsAssignableFrom(expression.Type)) 36 | throw new ArgumentOutOfRangeException("expression"); 37 | 38 | this.provider = provider; 39 | this.expression = expression; 40 | } 41 | 42 | Expression IQueryable.Expression 43 | { 44 | get { return this.expression; } 45 | } 46 | 47 | Type IQueryable.ElementType 48 | { 49 | get { return typeof(T); } 50 | } 51 | 52 | 53 | IQueryProvider IQueryable.Provider 54 | { 55 | get { return this.provider; } 56 | } 57 | 58 | public IEnumerator GetEnumerator() 59 | { 60 | return ((IEnumerable)this.provider.Execute(this.expression)).GetEnumerator(); 61 | } 62 | 63 | IEnumerator IEnumerable.GetEnumerator() 64 | { 65 | return ((IEnumerable)this.provider.Execute(this.expression)).GetEnumerator(); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /ElasticSearchQuery/Helpers/TypeSystem.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | 6 | namespace ElasticsearchQuery.Helpers 7 | { 8 | internal static class TypeSystem 9 | { 10 | 11 | 12 | internal static Type GetElementType(Type seqType) 13 | { 14 | 15 | 16 | Type ienum = FindIEnumerable(seqType); 17 | 18 | 19 | if (ienum == null) return seqType; 20 | 21 | 22 | return ienum.GetGenericArguments()[0]; 23 | 24 | 25 | } 26 | 27 | 28 | private static Type FindIEnumerable(Type seqType) 29 | { 30 | 31 | 32 | if (seqType == null || seqType == typeof(string)) 33 | 34 | 35 | return null; 36 | 37 | 38 | if (seqType.IsArray) 39 | 40 | 41 | return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); 42 | 43 | 44 | if (seqType.IsGenericType) 45 | { 46 | 47 | 48 | foreach (Type arg in seqType.GetGenericArguments()) 49 | { 50 | 51 | 52 | Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); 53 | 54 | 55 | if (ienum.IsAssignableFrom(seqType)) 56 | { 57 | 58 | 59 | return ienum; 60 | 61 | 62 | } 63 | 64 | 65 | } 66 | 67 | 68 | } 69 | 70 | 71 | Type[] ifaces = seqType.GetInterfaces(); 72 | 73 | 74 | if (ifaces != null && ifaces.Length > 0) 75 | { 76 | 77 | 78 | foreach (Type iface in ifaces) 79 | { 80 | 81 | 82 | Type ienum = FindIEnumerable(iface); 83 | 84 | 85 | if (ienum != null) return ienum; 86 | 87 | 88 | } 89 | 90 | 91 | } 92 | 93 | 94 | if (seqType.BaseType != null && seqType.BaseType != typeof(object)) 95 | { 96 | 97 | 98 | return FindIEnumerable(seqType.BaseType); 99 | 100 | 101 | } 102 | 103 | 104 | return null; 105 | 106 | 107 | } 108 | 109 | 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /ElasticSearchQuery/ElasticQueryMapper.cs: -------------------------------------------------------------------------------- 1 | using ElasticsearchQuery.Extensions; 2 | using Nest; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Reflection; 7 | using System.Text; 8 | 9 | namespace ElasticsearchQuery 10 | { 11 | public class ElasticQueryMapper 12 | { 13 | public static void Map(Type type, string index ,params string[] indexTypes) 14 | { 15 | if (TypeMaps.ContainsKey(type)) 16 | throw new InvalidOperationException($"The type {type.FullName} already has a map."); 17 | 18 | TypeMaps.Add(type, new ElasticIndexMap(index, indexTypes)); 19 | } 20 | 21 | /// 22 | /// Return the map for type, if not found will return a map with Type.Name in camelcase for index name and indexType and use the ElasticsearchTypeAttribute 23 | /// 24 | /// 25 | /// The Map for type 26 | public static ElasticIndexMap GetMap(Type type) 27 | { 28 | ElasticIndexMap map = null; 29 | if (TypeMaps.TryGetValue(type,out map)) 30 | return map; 31 | else 32 | { 33 | var typeNames = new List(); 34 | 35 | typeNames.Add(type.Name.ToLower()); 36 | 37 | var attrs = type.GetCustomAttributes() 38 | .Where(w => w is ElasticsearchTypeAttribute) 39 | .Select(s => s as ElasticsearchTypeAttribute); 40 | 41 | if (attrs.Any()) 42 | typeNames.AddRange(attrs.Select(s => s.Name.ToLower())); 43 | 44 | 45 | return new ElasticIndexMap(type.Name.ToLower(), typeNames.Distinct().ToArray()); 46 | }; 47 | 48 | } 49 | 50 | public static void Clean() 51 | { 52 | TypeMaps.Clear(); 53 | } 54 | 55 | private static IDictionary TypeMaps { get; set; } = new Dictionary(); 56 | } 57 | 58 | 59 | public class ElasticIndexMap 60 | { 61 | public ElasticIndexMap(string index, string[] indexTypes) 62 | { 63 | Index = index; 64 | IndexTypes = indexTypes; 65 | } 66 | 67 | public string Index { get;private set; } 68 | [Obsolete("As elasticsearch will not support more types this Will bee remove in next releases.")] 69 | public string[] IndexTypes { get; private set; } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 20 * * 0' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['csharp'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | with: 35 | # We must fetch at least the immediate parents so that if this is 36 | # a pull request then we can checkout the head. 37 | fetch-depth: 2 38 | 39 | # If this run was triggered by a pull request event, then checkout 40 | # the head of the pull request instead of the merge commit. 41 | - run: git checkout HEAD^2 42 | if: ${{ github.event_name == 'pull_request' }} 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /ElasticSearchQuery/ElasticQueryProvider.cs: -------------------------------------------------------------------------------- 1 | using ElasticsearchQuery.Extensions; 2 | using ElasticsearchQuery.Helpers; 3 | using Nest; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Reflection; 9 | using System.Text; 10 | 11 | namespace ElasticsearchQuery 12 | { 13 | internal class ElasticQueryProvider : QueryProvider 14 | { 15 | private readonly IElasticClient _elasticClient; 16 | public ElasticQueryProvider(IElasticClient elasticClient) 17 | { 18 | _elasticClient = elasticClient; 19 | } 20 | public override object Execute(Expression expression) 21 | { 22 | //Element type of IQueryable 23 | //Need this for the elastic search request 24 | Type elementType = TypeSystem.GetElementType(expression.Type); 25 | Type expType = TypeSystem.GetElementType(expression.Type); 26 | 27 | if (Attribute.IsDefined(expType, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false) 28 | && expType.IsGenericType && expType.Name.Contains("AnonymousType") 29 | && (expType.Name.StartsWith("<>") || expType.Name.StartsWith("VB$")) 30 | && (expType.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic) 31 | { 32 | var mExp = expression as MethodCallExpression; 33 | var t1 = TypeSystem.GetElementType(mExp.Arguments[0].Type) ; 34 | 35 | while (t1.IsGenericType) 36 | { 37 | mExp = mExp.Arguments[0] as MethodCallExpression; 38 | t1 = TypeSystem.GetElementType(mExp.Arguments[0].Type); 39 | } 40 | 41 | elementType = t1; 42 | } 43 | 44 | //Whem use IQueryable.Sum() for example need make this to get the elementType 45 | if (!elementType.IsClass) 46 | { 47 | var exp = expression as MethodCallExpression; 48 | elementType = exp.Arguments[0].Type.GenericTypeArguments[0]; 49 | } 50 | 51 | var elasticQueryResult = new QueryTranslator().Translate(expression, elementType); 52 | 53 | var method = typeof(ElasticClient) 54 | .GetMethods() 55 | .Where(m => m.Name == "Search") 56 | .Select(m => new 57 | { 58 | Method = m, 59 | Params = m.GetParameters(), 60 | Args = m.GetGenericArguments() 61 | }) 62 | .Where(x => x.Params.Length == 1 63 | && x.Args.Length == 1 64 | && x.Params.First().ParameterType == typeof(ISearchRequest)) 65 | .Select(x => x.Method).First(); 66 | 67 | MethodInfo generic = method.MakeGenericMethod(elementType); 68 | dynamic request = generic.Invoke(_elasticClient, new object[] { elasticQueryResult.SearchRequest }); 69 | 70 | 71 | if (elasticQueryResult.ReturnNumberOfRows) 72 | { 73 | return Convert.ChangeType(request.HitsMetadata.Total.Value, expType); 74 | } 75 | 76 | var closedGeneric = typeof(SearchResponse<>).MakeGenericType(elementType); 77 | 78 | //Simple Agregation 79 | if (!expType.IsClass) 80 | { 81 | var prop = closedGeneric.GetProperty("Aggregations"); 82 | var aggs = prop.GetValue(request) as AggregateDictionary; 83 | 84 | if (aggs.Any()) 85 | { 86 | var valueAgg = aggs.First().Value as ValueAggregate; 87 | return ConveterToType(expType, valueAgg.Value); 88 | } 89 | return ConveterToType(expType, 0); 90 | } 91 | else 92 | { 93 | 94 | if (elasticQueryResult.GroupBy.Any() || elasticQueryResult.Aggregation.Any()) 95 | { 96 | var mExp = expression as MethodCallExpression; 97 | var lastLambExp = ExpressionHelper.StripQuotes(mExp.Arguments.Last()) as LambdaExpression; 98 | 99 | var prop = closedGeneric.GetProperty("Aggregations"); 100 | var aggs = prop.GetValue(request) as AggregateDictionary; 101 | 102 | var resultAgg = ConvertAggregateResult(aggs); 103 | 104 | if (lastLambExp.Body is NewExpression) 105 | { 106 | var newExp = lastLambExp.Body as NewExpression; 107 | 108 | //A set of items 109 | if (expression.Type.GetInterfaces().Any(t => t == typeof(IQueryable) || t == typeof(IQueryable<>) )) 110 | { 111 | var typeList = typeof(List<>).MakeGenericType(expType); 112 | var list = Activator.CreateInstance(typeList); 113 | 114 | if (!resultAgg.Any()) 115 | return list; 116 | 117 | var addMethod = typeList.GetMethod("Add"); 118 | 119 | var membersExps = newExp.Arguments.Where(s => (s is MemberExpression)) 120 | .Select(s => s as MemberExpression) 121 | .Select(s => s.Member.Name.ToCamelCase()); 122 | 123 | var methodCallsExps = newExp.Arguments.Where(s => (s is MethodCallExpression)).Select(s => s as MethodCallExpression) .Select(s => s.Method.Name + "_" + ((s.Arguments.Last() as LambdaExpression ).Body as MemberExpression).Member.Name.ToCamelCase()); 124 | 125 | 126 | Func filterPredicate = (string str) => 127 | { 128 | return membersExps.Contains(str) || methodCallsExps.Contains(str); 129 | }; 130 | 131 | if (membersExps.Count() == 1 && membersExps.First() == "key") 132 | { 133 | filterPredicate = (string str) => 134 | { 135 | return membersExps.Contains(str) || methodCallsExps.Contains(str); 136 | }; 137 | } 138 | 139 | var parametersInfo = newExp.Constructor.GetParameters(); 140 | 141 | foreach (var item in resultAgg) 142 | { 143 | var parameters = item.Where(w => membersExps.Contains(w.Key) || methodCallsExps.Contains(w.Key)).Select(s => s.Value).ToArray(); 144 | 145 | 146 | if (membersExps.Count() == 1 && membersExps.First() == "key") 147 | { 148 | parameters = new object[] { item.First().Value }.Concat(parameters).ToArray(); 149 | } 150 | 151 | for (int i = 0; i < parameters.Count(); i++) 152 | { 153 | parameters[i] = ConveterToType(parametersInfo.ElementAt(i).ParameterType, parameters[i]); 154 | } 155 | 156 | 157 | var obj = newExp.Constructor.Invoke(parameters.ToArray()); 158 | addMethod.Invoke(list, new object[] { obj }); 159 | } 160 | 161 | return list; 162 | } 163 | else 164 | { 165 | //Just one item 166 | 167 | if (!resultAgg.Any()) 168 | return null; 169 | 170 | var obj = newExp.Constructor.Invoke(resultAgg.First().Select(s => s.Value).ToArray()); 171 | return obj; 172 | } 173 | } 174 | 175 | throw new NotImplementedException("Need implement the anonymous projection on select"); 176 | } 177 | else 178 | { 179 | var prop = closedGeneric.GetProperty("Documents"); 180 | 181 | if (prop.PropertyType.GetGenericArguments().Count() == 1 && 182 | prop.PropertyType.GetGenericArguments() .First() == expType) 183 | { 184 | var value = prop.GetValue(request); 185 | return value; 186 | } 187 | else 188 | { 189 | throw new NotImplementedException("Need implement the anonymous projection on select"); 190 | } 191 | } 192 | } 193 | } 194 | 195 | private object ConveterToType(Type type, object value) 196 | { 197 | if (type == typeof(decimal)) 198 | { 199 | return Convert.ToDecimal(value); 200 | } 201 | else if (type == typeof(decimal?)) 202 | { 203 | if (value == null) 204 | return null; 205 | return Convert.ToDecimal(value); 206 | } 207 | else if (type == typeof(double)) 208 | { 209 | return Convert.ToDouble(value); 210 | } 211 | else if (type == typeof(double?)) 212 | { 213 | if (value == null) 214 | return null; 215 | return Convert.ToDouble(value); 216 | } 217 | else if (type == typeof(int)) 218 | { 219 | return Convert.ToInt32(value); 220 | } 221 | else if (type == typeof(int?)) 222 | { 223 | if (value == null) 224 | return null; 225 | return Convert.ToInt32(value); 226 | } 227 | else if (type == typeof(long)) 228 | { 229 | return Convert.ToInt64(value); 230 | } 231 | else if (type == typeof(long?)) 232 | { 233 | if (value == null) 234 | return null; 235 | return Convert.ToInt64(value); 236 | } 237 | return Convert.ChangeType(value, type); 238 | } 239 | 240 | 241 | /// 242 | /// Monta uma List> onde tem nome da aggregação e o valor 243 | /// 244 | /// Aggregates do retorno do elastic 245 | /// passe nulo na primeira chamada 246 | /// 247 | public List> ConvertAggregateResult(IReadOnlyDictionary aggregates, Dictionary props = null) 248 | { 249 | 250 | var list = new List>(); 251 | if (props == null) 252 | props = new Dictionary(); 253 | 254 | var add = false; 255 | foreach (var item in aggregates) 256 | { 257 | //Se o item for um bucket 258 | if (item.Value is BucketAggregate && !item.Key.EndsWith("Count")) 259 | { 260 | var bucket = item.Value as BucketAggregate; 261 | //Para receber as Aggregadas do item 262 | IReadOnlyDictionary _subAggregates = null; 263 | 264 | foreach (var itemBucket in bucket.Items) 265 | { 266 | if (props.Any(w => w.Key == item.Key)) 267 | props.Remove(item.Key); 268 | 269 | //Caso seja usado um novo tipo adicionar outra condição 270 | 271 | //Usado no TermsAggregation 272 | if (itemBucket is KeyedBucket) 273 | { 274 | var _temp = itemBucket as KeyedBucket; 275 | props.Add(item.Key, _temp.Key); 276 | //_subAggregates = _temp.Aggregations; 277 | 278 | var t = (from a in _temp.Keys 279 | join b in _temp.ToList() on a equals b.Key 280 | select new { Key = a, Value = b.Value }); 281 | var _dc = new Dictionary(); 282 | foreach (var _item in t) 283 | { 284 | _dc.Add(_item.Key, _item.Value); 285 | } 286 | 287 | _subAggregates = new System.Collections.ObjectModel.ReadOnlyDictionary(_dc); 288 | } 289 | else if (itemBucket is RangeBucket) 290 | { 291 | var _temp = itemBucket as RangeBucket; 292 | props.Add(item.Key, _temp.Key); 293 | //_subAggregates = _temp.Aggregations; 294 | var t = (from a in _temp.Keys 295 | join b in _temp.ToList() on a equals b.Key 296 | select new { Key = a, Value = b.Value }); 297 | var _dc = new Dictionary(); 298 | foreach (var _item in t) 299 | { 300 | _dc.Add(_item.Key, _item.Value); 301 | } 302 | 303 | _subAggregates = new System.Collections.ObjectModel.ReadOnlyDictionary(_dc); 304 | } 305 | //Usado no DateHistogramAggregation 306 | else if (itemBucket is DateHistogramBucket) 307 | { 308 | var _temp = itemBucket as DateHistogramBucket; 309 | props.Add(item.Key, _temp.Date); 310 | //_subAggregates = _temp.Aggregations; 311 | var t = (from a in _temp.Keys 312 | join b in _temp.ToList() on a equals b.Key 313 | select new { Key = a, Value = b.Value }); 314 | var _dc = new Dictionary(); 315 | foreach (var _item in t) 316 | { 317 | _dc.Add(_item.Key, _item.Value); 318 | } 319 | 320 | _subAggregates = new System.Collections.ObjectModel.ReadOnlyDictionary(_dc); 321 | } 322 | 323 | list.AddRange(ConvertAggregateResult(_subAggregates, props)); 324 | } 325 | } 326 | //Quando ele for um Value considera sendo o ultimo nivel 327 | else if (item.Value is ValueAggregate) 328 | { 329 | add = true; 330 | var _temp = item.Value as ValueAggregate; 331 | 332 | if (props.Any(w => w.Key == item.Key)) 333 | props.Remove(item.Key); 334 | 335 | props.Add(item.Key, _temp.Value); 336 | } 337 | else if (item.Value is BucketAggregate && item.Key.EndsWith("Count")) 338 | { 339 | add = true; 340 | var _temp = item.Value as BucketAggregate; 341 | 342 | if (props.Any(w => w.Key == item.Key)) 343 | props.Remove(item.Key); 344 | 345 | props.Add(item.Key, _temp.Items.Select(s => (s as KeyedBucket).Key).Distinct().Count()); 346 | } 347 | } 348 | 349 | //Adicionar o item na lista 350 | if (add) 351 | { 352 | var _temp = new Dictionary(); 353 | 354 | foreach (var item in props) 355 | _temp.Add(item.Key, item.Value); 356 | 357 | list.Add(_temp); 358 | } 359 | 360 | return list; 361 | } 362 | } 363 | } 364 | -------------------------------------------------------------------------------- /ElasticSearchQuery.Tests/QueryTests.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using Nest; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading; 7 | using ElasticsearchQuery.Extensions; 8 | using Xunit; 9 | 10 | namespace ElasticsearchQuery.Tests 11 | { 12 | public class QueryTests 13 | { 14 | private IElasticClient ObterCliente() 15 | { 16 | // docker run --name elasticsearch --restart=always -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -d docker.elastic.co/elasticsearch/elasticsearch-oss:7.6.1 17 | var node = new Uri("http://localhost:9200/"); 18 | var settings = new ConnectionSettings(node); 19 | settings.ThrowExceptions(); 20 | settings.EnableDebugMode(); 21 | settings.DefaultMappingFor(m => m.IdProperty(p => p.ProductId)); 22 | var client = new ElasticClient(settings); 23 | return client; 24 | } 25 | 26 | private void CreateIndexTest(IElasticClient client, string indexName = "producttest" , string indexType = "producttest") 27 | { 28 | client.Indices.Create(indexName, cr => 29 | cr.Map( m => 30 | m.AutoMap() 31 | .Properties(ps => ps 32 | .Text(p => p.Name(na => na.ProductId).Analyzer("keyword").Fielddata(true)) 33 | .Text(p => p.Name(na => na.Name).Analyzer("keyword").Fielddata(true)) 34 | .Text(p => p.Name(na => na.NameAsText).Analyzer("standard").Fielddata(true)) 35 | .Number(p => p.Name(na => na.Price).Type(NumberType.Double)) 36 | ))); 37 | } 38 | 39 | private void AddData(params ProductTest[] data) 40 | { 41 | var client = ObterCliente(); 42 | 43 | if (client.Indices.Exists(Indices.Index("producttest")).Exists) 44 | client.DeleteByQuery(a => a.Query(q => q.MatchAll()) 45 | .Index("producttest")); 46 | else 47 | CreateIndexTest(client); 48 | 49 | client.IndexMany(data, "producttest"); 50 | 51 | client.Indices.Refresh("producttest"); 52 | } 53 | 54 | private IEnumerable GenerateData(int size, params ProductTest[] additionalData) 55 | { 56 | var testsProducts = new Faker("pt_BR") 57 | .RuleFor(o => o.Name ,f => f.Commerce.ProductName()) 58 | .RuleFor(o => o.Price, f => f.Finance.Amount(1)) 59 | .RuleFor(o => o.ProductId, f => Guid.NewGuid()) 60 | .FinishWith((f, p) => 61 | { 62 | p.NameAsText = p.Name; 63 | }); 64 | 65 | return testsProducts.Generate(size).Union(additionalData); 66 | } 67 | 68 | [Theory] 69 | [InlineData("customindex", "customindex")] 70 | [InlineData("mycustomidx", "mycustomidx")] 71 | [InlineData("customindex", "mycustomidx")] 72 | [InlineData("productindex", "productindextype")] 73 | public void UsingCustomMapper(string indexName , string indexType) 74 | { 75 | var productList = GenerateData(1000); 76 | 77 | var client = ObterCliente(); 78 | 79 | if (client.Indices.Exists(indexName).Exists) 80 | client.Indices.Delete(indexName); 81 | 82 | CreateIndexTest(client, indexName, indexType); 83 | 84 | client.IndexMany(productList, indexName); 85 | client.Indices.Refresh(indexName); 86 | 87 | ElasticQueryMapper.Map(typeof(ProductTest), indexName, indexType); 88 | 89 | var query = ElasticSearchQueryFactory.CreateQuery(client); 90 | var result = query.ToList(); 91 | Assert.NotEmpty(result); 92 | ElasticQueryMapper.Clean(); 93 | } 94 | 95 | [Fact] 96 | public void WhereWithCollectionContainsMethod() 97 | { 98 | 99 | var products = new ProductTest[] 100 | { 101 | new ProductTest(Guid.NewGuid(), "Product A", 99), 102 | new ProductTest(Guid.NewGuid(), "Product B", 150), 103 | new ProductTest(Guid.NewGuid(), "Product C", 200), 104 | new ProductTest(Guid.NewGuid(), "Product D", 300) 105 | }; 106 | 107 | var productList = GenerateData(1000, products); 108 | 109 | AddData(productList.ToArray()); 110 | 111 | var client = ObterCliente(); 112 | 113 | var query = ElasticSearchQueryFactory.CreateQuery(client); 114 | 115 | var productsIds = products.Select(s => s.ProductId).ToList(); 116 | 117 | query = query.Where(w => productsIds.Contains(w.ProductId)); 118 | 119 | var result = query.ToList(); 120 | Assert.NotEmpty(result); 121 | Assert.True(result.All(a => products.Any(p => p.ProductId == a.ProductId))); 122 | } 123 | 124 | [Fact] 125 | public void OrderByAndWhere() 126 | { 127 | var product = new ProductTest(Guid.NewGuid(), "Product A", 99); 128 | 129 | var productList = GenerateData(1000, product); 130 | 131 | AddData(productList.ToArray()); 132 | var client = ObterCliente(); 133 | 134 | var query = ElasticSearchQueryFactory.CreateQuery(client); 135 | 136 | query = query.Where(w => w.Price == 99).OrderBy(o => o.Name).ThenBy(o => o.Price); 137 | 138 | var result = query.ToList(); 139 | Assert.NotEmpty(result); 140 | Assert.Contains(result, f=> f.ProductId == product.ProductId); 141 | Assert.Equal(99, result.First().Price); 142 | } 143 | 144 | [Fact] 145 | public void MatchPhrase() 146 | { 147 | var product = new ProductTest(Guid.NewGuid(), "Product of category", 99); 148 | 149 | var productList = GenerateData(1000, product); 150 | 151 | AddData(productList.ToArray()); 152 | var client = ObterCliente(); 153 | 154 | var query = ElasticSearchQueryFactory.CreateQuery(client); 155 | 156 | query = query.Where(w => w.NameAsText.MatchPhrase("of category")); 157 | 158 | var result = query.ToList(); 159 | Assert.NotEmpty(result); 160 | Assert.Contains(result, f => f.ProductId == product.ProductId); 161 | Assert.Equal(99, result.First().Price); 162 | } 163 | 164 | [Fact] 165 | public void MatchPhraseDeny() 166 | { 167 | var product = new ProductTest(Guid.NewGuid(), "Product of category", 99); 168 | 169 | var productList = GenerateData(1000, product); 170 | 171 | AddData(productList.ToArray()); 172 | var client = ObterCliente(); 173 | 174 | var query = ElasticSearchQueryFactory.CreateQuery(client); 175 | 176 | query = query.Where(w => !w.NameAsText.MatchPhrase("of category")); 177 | 178 | var result = query.ToList(); 179 | Assert.NotEmpty(result); 180 | Assert.DoesNotContain(result, f => f.ProductId == product.ProductId); 181 | } 182 | 183 | [Fact] 184 | public void MultiMatch() 185 | { 186 | var product = new ProductTest(Guid.NewGuid(), "Product of category", 99); 187 | 188 | var productList = GenerateData(1000, product); 189 | 190 | AddData(productList.ToArray()); 191 | var client = ObterCliente(); 192 | 193 | var query = ElasticSearchQueryFactory.CreateQuery(client); 194 | 195 | query = query.Where(w => w.MultiMatch("category",t => t.NameAsText,t => t.Name)); 196 | 197 | var result = query.ToList(); 198 | Assert.NotEmpty(result); 199 | Assert.Contains(result, f => f.ProductId == product.ProductId); 200 | Assert.Equal(99, result.First().Price); 201 | } 202 | 203 | [Fact] 204 | public void MultiMatchDeny() 205 | { 206 | var product = new ProductTest(Guid.NewGuid(), "Product of category", 99); 207 | 208 | var productList = GenerateData(1000, product); 209 | 210 | AddData(productList.ToArray()); 211 | var client = ObterCliente(); 212 | 213 | var query = ElasticSearchQueryFactory.CreateQuery(client); 214 | 215 | query = query.Where(w => !w.MultiMatch("category", t => t.NameAsText, t => t.Name)); 216 | 217 | var result = query.ToList(); 218 | Assert.NotEmpty(result); 219 | Assert.DoesNotContain(result, f => f.ProductId == product.ProductId); 220 | } 221 | 222 | [Fact] 223 | public void Exists() 224 | { 225 | var product = new ProductTest(Guid.NewGuid(), null, 99); 226 | 227 | var productList = GenerateData(1000, product); 228 | 229 | AddData(productList.ToArray()); 230 | var client = ObterCliente(); 231 | 232 | var query = ElasticSearchQueryFactory.CreateQuery(client); 233 | 234 | query = query.Where(w => w.Exists(t => t.NameAsText)); 235 | 236 | var result = query.ToList(); 237 | Assert.NotEmpty(result); 238 | Assert.DoesNotContain(result, f => f.ProductId == product.ProductId); 239 | } 240 | 241 | [Fact] 242 | public void OrderBy() 243 | { 244 | var productList = GenerateData(1000); 245 | 246 | AddData(productList.ToArray()); 247 | var client = ObterCliente(); 248 | 249 | var query = ElasticSearchQueryFactory.CreateQuery(client); 250 | 251 | query = query.OrderBy(o => o.Name).ThenBy(o => o.Price); 252 | 253 | var result = query.ToList(); 254 | 255 | var product = productList.OrderBy(o => o.Name).ThenBy(o => o.Price).First(); 256 | 257 | Assert.NotEmpty(result); 258 | Assert.Contains(result, f => f.ProductId == product.ProductId); 259 | Assert.Equal(product.Price, result.First().Price); 260 | } 261 | 262 | [Fact] 263 | public void OrderByDescendingAndWhere() 264 | { 265 | var product = new ProductTest(Guid.NewGuid(), "Product A", 150); 266 | 267 | var productList = GenerateData(1000, product); 268 | 269 | AddData(productList.ToArray()); 270 | var client = ObterCliente(); 271 | 272 | 273 | var query = ElasticSearchQueryFactory.CreateQuery(client); 274 | 275 | query = query.Where(w => w.Price == 150).OrderByDescending(o => o.Name).ThenByDescending(o => o.Price); 276 | 277 | var result = query.ToList(); 278 | Assert.Contains(result, f => f.ProductId == product.ProductId); 279 | Assert.Equal(product.Price, result.First().Price); 280 | } 281 | 282 | [Fact] 283 | public void OrderByDescending() 284 | { 285 | var productList = GenerateData(1000); 286 | 287 | AddData(productList.ToArray()); 288 | 289 | var client = ObterCliente(); 290 | 291 | var query = ElasticSearchQueryFactory.CreateQuery(client); 292 | 293 | query = query.OrderByDescending(o => o.Name).ThenByDescending(o => o.Price); 294 | var product = productList.OrderByDescending(o => o.Name).ThenByDescending(o => o.Price).First(); 295 | 296 | var result = query.ToList(); 297 | 298 | Assert.NotEmpty(result); 299 | Assert.Contains(result, f => f.ProductId == product.ProductId); 300 | Assert.Equal(product.Price, result.First().Price); 301 | } 302 | 303 | [Theory] 304 | [InlineData(0,10)] 305 | [InlineData(5, 50)] 306 | [InlineData(50, 30)] 307 | public void TakeSkipValid(int skip , int take) 308 | { 309 | var productList = GenerateData(1000); 310 | 311 | AddData(productList.ToArray()); 312 | 313 | var client = ObterCliente(); 314 | 315 | var query = ElasticSearchQueryFactory.CreateQuery(client); 316 | 317 | query = query.Take(take).Skip(skip); 318 | 319 | var result = query.ToList(); 320 | Assert.NotEmpty(result); 321 | Assert.Equal(take, result.Count); 322 | } 323 | 324 | [Fact] 325 | public void EndsWithDeny() 326 | { 327 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 328 | 329 | var productList = GenerateData(1000, produto); 330 | 331 | AddData(productList.ToArray()); 332 | 333 | var client = ObterCliente(); 334 | 335 | var pId = produto.ProductId; 336 | var pNome = produto.Name; 337 | 338 | var query = ElasticSearchQueryFactory.CreateQuery(client); 339 | query = query.Where(w => !w.Name.EndsWith("Test")); 340 | 341 | var result = query.ToList(); 342 | Assert.NotEmpty(result); 343 | Assert.DoesNotContain(result, f => f.ProductId == pId); 344 | } 345 | 346 | [Fact] 347 | public void EndsWithValid() 348 | { 349 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 350 | 351 | var productList = GenerateData(1000, produto); 352 | 353 | AddData(productList.ToArray()); 354 | 355 | var client = ObterCliente(); 356 | 357 | var pId = produto.ProductId; 358 | var pNome = produto.Name; 359 | 360 | var query = ElasticSearchQueryFactory.CreateQuery(client); 361 | query = query.Where(w => w.Name.EndsWith("st")); 362 | 363 | var result = query.ToList(); 364 | Assert.NotEmpty(result); 365 | Assert.Contains(result, f => f.ProductId == pId); 366 | } 367 | 368 | [Fact] 369 | public void EndsWithInvalid() 370 | { 371 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 372 | 373 | AddData(produto); 374 | 375 | var client = ObterCliente(); 376 | 377 | var pId = produto.ProductId; 378 | var pNome = produto.Name; 379 | 380 | var query = ElasticSearchQueryFactory.CreateQuery(client); 381 | query = query.Where(w => w.Name.EndsWith("zzzzzzz")); 382 | 383 | var result = query.ToList(); 384 | Assert.Empty(result); 385 | } 386 | 387 | [Fact] 388 | public void StartsWithDeny() 389 | { 390 | var produto = new ProductTest(Guid.NewGuid(), "TestProduct", 9.9M); 391 | 392 | var productList = GenerateData(1000, produto); 393 | 394 | AddData(productList.ToArray()); 395 | 396 | var client = ObterCliente(); 397 | 398 | var pId = produto.ProductId; 399 | var pNome = produto.Name; 400 | 401 | var query = ElasticSearchQueryFactory.CreateQuery(client); 402 | query = query.Where(w => !w.Name.StartsWith("Test")); 403 | 404 | var result = query.ToList(); 405 | Assert.NotEmpty(result); 406 | Assert.DoesNotContain(result, f => f.ProductId == pId); 407 | } 408 | 409 | [Fact] 410 | public void StartsWithValid() 411 | { 412 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 413 | 414 | var productList = GenerateData(1000, produto); 415 | 416 | AddData(productList.ToArray()); 417 | 418 | var client = ObterCliente(); 419 | 420 | var pId = produto.ProductId; 421 | var pNome = produto.Name; 422 | 423 | var query = ElasticSearchQueryFactory.CreateQuery(client); 424 | query = query.Where(w => w.Name.StartsWith("Prod")); 425 | 426 | var result = query.ToList(); 427 | Assert.NotEmpty(result); 428 | Assert.Contains(result, f => f.ProductId == pId); 429 | } 430 | 431 | [Fact] 432 | public void StartsWithInvalid() 433 | { 434 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 435 | 436 | var productList = GenerateData(1000, produto); 437 | 438 | AddData(productList.ToArray()); 439 | 440 | var client = ObterCliente(); 441 | 442 | var pId = produto.ProductId; 443 | var pNome = produto.Name; 444 | 445 | var query = ElasticSearchQueryFactory.CreateQuery(client); 446 | query = query.Where(w => w.Name.StartsWith("zzzzzzzzzzz")); 447 | 448 | var result = query.ToList(); 449 | Assert.Empty(result); 450 | } 451 | 452 | 453 | [Fact] 454 | public void ContainsDeny() 455 | { 456 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 457 | 458 | AddData(produto); 459 | 460 | var client = ObterCliente(); 461 | 462 | var pId = produto.ProductId; 463 | var pNome = produto.Name; 464 | 465 | var query = ElasticSearchQueryFactory.CreateQuery(client); 466 | query = query.Where(w => !w.Name.Contains("Test")); 467 | 468 | var result = query.ToList(); 469 | Assert.Empty(result); 470 | Assert.DoesNotContain(result, f => f.ProductId == pId); 471 | } 472 | 473 | [Fact] 474 | public void ContainsValid() 475 | { 476 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 477 | 478 | AddData(produto); 479 | 480 | var client = ObterCliente(); 481 | 482 | var pId = produto.ProductId; 483 | var pNome = produto.Name; 484 | 485 | var query = ElasticSearchQueryFactory.CreateQuery(client); 486 | query = query.Where(w => w.Name.Contains("Test")); 487 | 488 | var result = query.ToList(); 489 | Assert.NotEmpty(result); 490 | Assert.Contains(result, f => f.ProductId == pId); 491 | } 492 | 493 | [Fact] 494 | public void ContainsInvalid() 495 | { 496 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 497 | 498 | AddData(produto); 499 | 500 | var client = ObterCliente(); 501 | 502 | var pId = produto.ProductId; 503 | var pNome = produto.Name; 504 | 505 | var query = ElasticSearchQueryFactory.CreateQuery(client); 506 | query = query.Where(w => w.Name.Contains("Coca-Cola")); 507 | 508 | var result = query.ToList(); 509 | Assert.Empty(result); 510 | } 511 | 512 | [Fact] 513 | public void NotEqualsValid() 514 | { 515 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 516 | 517 | AddData(produto); 518 | 519 | var client = ObterCliente(); 520 | 521 | var pId = produto.ProductId; 522 | var pNome = produto.Name; 523 | 524 | var query = ElasticSearchQueryFactory.CreateQuery(client); 525 | query = query.Where(w => w.ProductId != Guid.Empty); 526 | 527 | var result = query.ToList(); 528 | Assert.NotEmpty(result); 529 | Assert.Contains(result, f => f.ProductId == pId); 530 | } 531 | 532 | [Fact] 533 | public void NotEqualsDeny() 534 | { 535 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 536 | 537 | AddData(produto); 538 | 539 | var client = ObterCliente(); 540 | 541 | var pId = produto.ProductId; 542 | var pNome = produto.Name; 543 | 544 | var query = ElasticSearchQueryFactory.CreateQuery(client); 545 | query = query.Where(w => !(w.ProductId != Guid.Empty)); 546 | 547 | var result = query.ToList(); 548 | Assert.Empty(result); 549 | Assert.DoesNotContain(result, f => f.ProductId == pId); 550 | } 551 | 552 | 553 | [Fact] 554 | public void NotEqualsInvalid() 555 | { 556 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 557 | 558 | AddData(produto); 559 | 560 | var client = ObterCliente(); 561 | 562 | var pId = produto.ProductId; 563 | var pNome = produto.Name; 564 | 565 | var query = ElasticSearchQueryFactory.CreateQuery(client); 566 | query = query.Where(w => w.ProductId != pId); 567 | 568 | var result = query.ToList(); 569 | Assert.Empty(result); 570 | } 571 | 572 | [Fact] 573 | public void EqualsDeny() 574 | { 575 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 576 | 577 | AddData(produto); 578 | 579 | var client = ObterCliente(); 580 | 581 | var pId = produto.ProductId; 582 | var pNome = produto.Name; 583 | 584 | var query = ElasticSearchQueryFactory.CreateQuery(client); 585 | query = query.Where(w => !(w.ProductId == pId)); 586 | 587 | var result = query.ToList(); 588 | Assert.Empty(result); 589 | Assert.DoesNotContain(result, f => f.ProductId == pId); 590 | } 591 | 592 | [Fact] 593 | public void EqualsValid() 594 | { 595 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 596 | 597 | AddData(produto); 598 | 599 | var client = ObterCliente(); 600 | 601 | var pId = produto.ProductId; 602 | var pNome = produto.Name; 603 | 604 | var query = ElasticSearchQueryFactory.CreateQuery(client); 605 | query = query.Where(w => w.ProductId == pId); 606 | 607 | var result = query.ToList(); 608 | Assert.NotEmpty(result); 609 | Assert.Contains(result, f => f.ProductId == pId); 610 | } 611 | 612 | [Fact] 613 | public void EqualsInvalid() 614 | { 615 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 616 | 617 | AddData(produto); 618 | 619 | var client = ObterCliente(); 620 | 621 | var pId = produto.ProductId; 622 | var pNome = produto.Name; 623 | 624 | var query = ElasticSearchQueryFactory.CreateQuery(client); 625 | query = query.Where(w => w.ProductId == Guid.Empty); 626 | 627 | var result = query.ToList(); 628 | Assert.Empty(result); 629 | } 630 | 631 | [Fact] 632 | public void GreaterThanInvalid() 633 | { 634 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 635 | 636 | AddData(produto); 637 | 638 | var client = ObterCliente(); 639 | 640 | var query = ElasticSearchQueryFactory.CreateQuery(client); 641 | query = query.Where(w => w.Price > 50); 642 | 643 | var result = query.ToList(); 644 | Assert.Empty(result); 645 | } 646 | 647 | [Fact] 648 | public void GreaterThanValid() 649 | { 650 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 651 | 652 | AddData(produto); 653 | 654 | var client = ObterCliente(); 655 | 656 | var pId = produto.ProductId; 657 | 658 | var query = ElasticSearchQueryFactory.CreateQuery(client); 659 | query = query.Where(w => w.Price > 1); 660 | 661 | var result = query.ToList(); 662 | Assert.NotEmpty(result); 663 | Assert.Contains(result, f => f.ProductId == pId); 664 | } 665 | 666 | [Fact] 667 | public void LessThanValid() 668 | { 669 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 670 | 671 | AddData(produto); 672 | 673 | var client = ObterCliente(); 674 | 675 | var pId = produto.ProductId; 676 | 677 | var query = ElasticSearchQueryFactory.CreateQuery(client); 678 | query = query.Where(w => w.Price < 50); 679 | 680 | var result = query.ToList(); 681 | Assert.NotEmpty(result); 682 | Assert.Contains(result, f => f.ProductId == pId); 683 | } 684 | 685 | [Fact] 686 | public void LessThanDeny() 687 | { 688 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 689 | 690 | AddData(produto); 691 | 692 | var client = ObterCliente(); 693 | 694 | var pId = produto.ProductId; 695 | 696 | var query = ElasticSearchQueryFactory.CreateQuery(client); 697 | query = query.Where(w => !(w.Price < 50)); 698 | 699 | var result = query.ToList(); 700 | Assert.Empty(result); 701 | Assert.DoesNotContain(result, f => f.ProductId == pId); 702 | } 703 | 704 | 705 | [Fact] 706 | public void LessThanInvalid() 707 | { 708 | var produto = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 709 | 710 | AddData(produto); 711 | 712 | var client = ObterCliente(); 713 | 714 | var query = ElasticSearchQueryFactory.CreateQuery(client); 715 | query = query.Where(w => w.Price < 1); 716 | 717 | var result = query.ToList(); 718 | Assert.Empty(result); 719 | } 720 | 721 | [Fact] 722 | public void AggregationSum() 723 | { 724 | var produto1 = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 725 | var produto2 = new ProductTest(Guid.NewGuid(), "ProductTest 2", 5M); 726 | 727 | AddData(produto1, produto2); 728 | 729 | var client = ObterCliente(); 730 | 731 | var query = ElasticSearchQueryFactory.CreateQuery(client); 732 | var totalPrice = query.Sum(s => s.Price); 733 | 734 | Assert.Equal(produto1.Price + produto2.Price, totalPrice); 735 | } 736 | 737 | [Fact] 738 | public void AggregationCount() 739 | { 740 | var produto1 = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 741 | var produto2 = new ProductTest(Guid.NewGuid(), "ProductTest 2", 5M); 742 | 743 | AddData(produto1, produto2); 744 | 745 | var client = ObterCliente(); 746 | 747 | var query = ElasticSearchQueryFactory.CreateQuery(client); 748 | var count = query.Count(); 749 | 750 | Assert.Equal(2, count); 751 | } 752 | 753 | [Fact] 754 | public void AggregationCountWithCoditions() 755 | { 756 | var produto1 = new ProductTest(Guid.NewGuid(), "ProductTest", 25.5M); 757 | var produto2 = new ProductTest(Guid.NewGuid(), "ProductTest 2", 5M); 758 | var produto3 = new ProductTest(Guid.NewGuid(), "ProductTest 3", 6M); 759 | var produto4 = new ProductTest(Guid.NewGuid(), "ProductTest 4", 7M); 760 | var produto5 = new ProductTest(Guid.NewGuid(), "ProductTest 5", 8M); 761 | 762 | AddData(produto1, produto2, produto3, produto4, produto5); 763 | 764 | var client = ObterCliente(); 765 | 766 | var query = ElasticSearchQueryFactory.CreateQuery(client); 767 | var count = query.Where(w => w.Price < 10M).Count(); 768 | 769 | Assert.Equal(4, count); 770 | } 771 | 772 | [Fact] 773 | public void LinqSum() 774 | { 775 | var produto1 = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 776 | var produto2 = new ProductTest(Guid.NewGuid(), "ProductTest 2", 5M); 777 | 778 | AddData(produto1, produto2); 779 | 780 | var client = ObterCliente(); 781 | 782 | var query = ElasticSearchQueryFactory.CreateQuery(client); 783 | var result = (from o in query 784 | group o by o.Name into g 785 | select new 786 | { 787 | Produto = g.Key, 788 | Total = g.Sum(o => o.Price), 789 | Min = g.Min(o => o.Price), 790 | Avg = g.Average(o => o.Price) 791 | }).ToList(); 792 | 793 | Assert.Equal(produto1.Price + produto2.Price, result.Sum(s => s.Total)); 794 | } 795 | 796 | [Fact] 797 | public void LinqNewGroupSum() 798 | { 799 | var produto1 = new ProductTest(Guid.NewGuid(), "ProductTest", 9.9M); 800 | var produto2 = new ProductTest(Guid.NewGuid(), "ProductTest 2", 5M); 801 | 802 | AddData(produto1, produto2); 803 | 804 | var client = ObterCliente(); 805 | 806 | var query = ElasticSearchQueryFactory.CreateQuery(client); 807 | 808 | var result = (from o in query 809 | group o by new { o.Name, o.ProductId } into g 810 | select new 811 | { 812 | Produto = g.Key.Name, 813 | Total = g.Sum(o => o.Price), 814 | Min = g.Min(o => o.Price), 815 | Avg = g.Average(o => o.Price) 816 | }).ToList(); 817 | 818 | Assert.Equal(produto1.Price + produto2.Price, result.Sum(s => s.Total)); 819 | } 820 | } 821 | 822 | [ElasticsearchType(Name= "producttest")] 823 | public class ProductTest 824 | { 825 | public ProductTest() 826 | { 827 | 828 | } 829 | public ProductTest(Guid productId, string name, decimal price) 830 | { 831 | ProductId = productId; 832 | Name = name; 833 | NameAsText = name; 834 | Price = price; 835 | } 836 | 837 | public Guid ProductId { get; set; } 838 | public string Name { get; set; } 839 | public string NameAsText { get; set; } 840 | public decimal Price { get; set; } 841 | } 842 | } 843 | -------------------------------------------------------------------------------- /ElasticSearchQuery/QueryTranslator.cs: -------------------------------------------------------------------------------- 1 | using ElasticsearchQuery.Extensions; 2 | using ElasticsearchQuery.Helpers; 3 | using Nest; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Reflection; 9 | 10 | namespace ElasticsearchQuery 11 | { 12 | internal class QueryTranslator : ExpressionVisitor 13 | { 14 | SearchRequest _searchRequest; 15 | QueryContainer queryContainer; 16 | string field = string.Empty; 17 | List fieldsGroupBy = new List(); 18 | List aggregations = new List(); 19 | List fieldsOrderBy = new List(); 20 | private bool returnNumberOfRows = false; 21 | string operacao = string.Empty; 22 | ExpressionType binaryExpType; 23 | object value = null; 24 | private bool AndCondition = true; 25 | Type elementType; 26 | bool denyCondition = false; 27 | 28 | 29 | private AggregationBase _aggregationBase; 30 | 31 | public AggregationBase AggregationBase 32 | { 33 | get { return _aggregationBase; } 34 | set 35 | { 36 | if (_aggregationBase == null) 37 | _aggregationBase = value; 38 | else 39 | _aggregationBase = _aggregationBase && value; 40 | } 41 | } 42 | 43 | internal QueryTranslator() 44 | { 45 | 46 | } 47 | 48 | public AggregationDictionary ObterAgrupamentoNest(IEnumerable agrupamentos, AggregationBase aggregations = null) 49 | { 50 | foreach (var aggr in agrupamentos) 51 | { 52 | 53 | //Tipos de agrupamento 54 | if (aggr.PropertyType == typeof(DateTime) 55 | || aggr.PropertyType == typeof(DateTime?)) 56 | { 57 | var dateHistAgg = new DateHistogramAggregation(aggr.Field) 58 | { 59 | Missing = (DateTime?)null,//(DateTime?)aggr.Missing, 60 | Field = aggr.Field, 61 | //Aggregations = ((aggregations != null) ? aggregations : null), 62 | Interval = DateInterval.Day, 63 | MinimumDocumentCount = 1, 64 | //Script = (!string.IsNullOrWhiteSpace(aggr.Script)) ? new InlineScript(aggr.Script) : null 65 | }; 66 | 67 | if (aggregations != null) 68 | dateHistAgg.Aggregations = aggregations; 69 | 70 | aggregations = dateHistAgg; 71 | } 72 | else 73 | { 74 | var termsAgg = new TermsAggregation(aggr.Field) 75 | { 76 | Field = aggr.Field, 77 | //Aggregations = ((aggregations != null) ? aggregations : null), 78 | Size = int.MaxValue, 79 | //Missing = null,//aggr.Missing, 80 | MinimumDocumentCount = 1, 81 | //Script = (!string.IsNullOrWhiteSpace(aggr.Script)) ? new InlineScript(aggr.Script) : null 82 | }; 83 | 84 | if (aggregations != null) 85 | termsAgg.Aggregations = aggregations; 86 | 87 | 88 | aggregations = termsAgg; 89 | } 90 | } 91 | return aggregations; 92 | } 93 | 94 | 95 | private void SetAggregation() 96 | { 97 | 98 | 99 | foreach (var item in aggregations) 100 | { 101 | switch (item.Method) 102 | { 103 | case "Count": 104 | AggregationBase = new ValueCountAggregation(item.AggName, item.Field); 105 | break; 106 | case "Min": 107 | AggregationBase = new MinAggregation(item.AggName, item.Field); 108 | break; 109 | case "Max": 110 | AggregationBase = new MaxAggregation(item.AggName, item.Field); 111 | break; 112 | case "Sum": 113 | AggregationBase = new SumAggregation(item.AggName, item.Field); 114 | break; 115 | case "Average": 116 | AggregationBase = new AverageAggregation(item.AggName, item.Field); 117 | break; 118 | default: 119 | break; 120 | } 121 | } 122 | 123 | _searchRequest.Aggregations = ObterAgrupamentoNest(fieldsGroupBy, AggregationBase); 124 | } 125 | 126 | private void SetTextSearch() 127 | { 128 | switch (operacao) 129 | { 130 | case "Contains": 131 | 132 | Func, IWildcardQuery> _containsSelector = f => f.Value("*" + value.ToString()).Field(field); 133 | 134 | if (denyCondition) 135 | queryContainer = Query.Bool(b => b.MustNot(m => m.Wildcard(_containsSelector))); 136 | else 137 | queryContainer = Query.Wildcard(_containsSelector); 138 | break; 139 | case "StartsWith": 140 | 141 | Func, IPrefixQuery> _startsWithSelector = f => f.Field(field).Value(value.ToString()); 142 | 143 | if (denyCondition) 144 | queryContainer = Query.Bool(b => b.MustNot(m => m.Prefix(_startsWithSelector))); 145 | else 146 | queryContainer = Query.Prefix(_startsWithSelector); 147 | break; 148 | case "EndsWith": 149 | 150 | Func, IRegexpQuery> _endsWithSelector = f => f.Field(field).Value(".*" + value.ToString()); 151 | 152 | if (denyCondition) 153 | queryContainer = Query.Bool(b => b.MustNot(m => m.Regexp(_endsWithSelector))); 154 | else 155 | queryContainer = Query.Regexp(_endsWithSelector); 156 | break; 157 | case "MatchPhrase": 158 | 159 | Func, IMatchPhraseQuery> _matchPhraseSelector = f => f.Field(field).Query(value.ToString()); 160 | 161 | if (denyCondition) 162 | queryContainer = Query.Bool(b => b.MustNot(m => m.MatchPhrase(_matchPhraseSelector))); 163 | else 164 | queryContainer = Query.MatchPhrase(_matchPhraseSelector); 165 | break; 166 | case "MultiMatch": 167 | var _fields = field.Split(';'); 168 | 169 | Func, IMultiMatchQuery> _multiMachSelector = f => f.Fields(_fields).Query(value.ToString()); 170 | 171 | if (denyCondition) 172 | queryContainer = Query.Bool(b => b.MustNot(m => m.MultiMatch(_multiMachSelector))); 173 | else 174 | queryContainer = Query.MultiMatch(_multiMachSelector); 175 | 176 | break; 177 | default: 178 | break; 179 | } 180 | 181 | if (_searchRequest.Query == null) 182 | { 183 | _searchRequest.Query = queryContainer; 184 | } 185 | else 186 | { 187 | if (AndCondition) 188 | { 189 | _searchRequest.Query = _searchRequest.Query && _searchRequest.Query; 190 | } 191 | else 192 | { 193 | _searchRequest.Query = _searchRequest.Query || _searchRequest.Query; 194 | } 195 | } 196 | } 197 | 198 | private void SetQuery() 199 | { 200 | switch (binaryExpType) 201 | { 202 | case ExpressionType.Equal: 203 | if (typeof(System.Collections.IEnumerable).IsAssignableFrom(value.GetType())) 204 | { 205 | var _tempCollection = value as System.Collections.IEnumerable; 206 | 207 | Func, ITermsQuery> _termsSelector = t => t.Field(field).Terms(_tempCollection); 208 | 209 | if (denyCondition) 210 | queryContainer = Query.Bool(b => b.MustNot(m => m.Terms(_termsSelector))); 211 | else 212 | queryContainer = Query.Terms(_termsSelector); 213 | } 214 | else 215 | { 216 | Func, ITermQuery> _termSelector = t => t.Field(field).Value(value); 217 | 218 | if (denyCondition) 219 | queryContainer = Query.Bool(b => b.MustNot(m => m.Term(_termSelector))); 220 | else 221 | queryContainer = Query.Term(_termSelector); 222 | } 223 | break; 224 | case ExpressionType.NotEqual: 225 | 226 | Func, ITermQuery> _notEqualTermSelector = t => t.Field(field).Value(value); 227 | 228 | if (denyCondition) 229 | queryContainer = Query.Term(_notEqualTermSelector); 230 | else 231 | queryContainer = Query.Bool(b => b.MustNot(m => m.Term(_notEqualTermSelector))); 232 | break; 233 | case ExpressionType.LessThan: 234 | //TODO cast only when is necessary to double / decimal 235 | Func, INumericRangeQuery> _lessThanSelector = r => r.Field(field).LessThan((double?)((decimal?)value)); 236 | if (denyCondition) 237 | queryContainer = Query.Bool(b => b.MustNot(m => m.Range(_lessThanSelector))); 238 | else 239 | queryContainer = Query.Range(_lessThanSelector); 240 | break; 241 | case ExpressionType.LessThanOrEqual: 242 | 243 | Func, INumericRangeQuery> _lessThanOrEqualSelector = r => r.Field(field).LessThanOrEquals((double?)((decimal?)value)); 244 | if (denyCondition) 245 | queryContainer = Query.Bool(b => b.MustNot(m => m.Range(_lessThanOrEqualSelector))); 246 | else 247 | queryContainer = Query.Range(_lessThanOrEqualSelector); 248 | break; 249 | case ExpressionType.GreaterThan: 250 | 251 | Func, INumericRangeQuery> _greaterThanSelector = r => r.Field(field).GreaterThan((double?)((decimal?)value)); 252 | if (denyCondition) 253 | queryContainer = Query.Bool(b => b.MustNot(m => m.Range(_greaterThanSelector))); 254 | else 255 | queryContainer = Query.Range(_greaterThanSelector); 256 | 257 | break; 258 | case ExpressionType.GreaterThanOrEqual: 259 | 260 | Func, INumericRangeQuery> _greaterThanOrEqualSelector = r => r.Field(field).GreaterThanOrEquals((double?)((decimal?)value)); 261 | if (denyCondition) 262 | queryContainer = Query.Bool(b => b.MustNot(m => m.Range(_greaterThanOrEqualSelector))); 263 | else 264 | queryContainer = Query.Range(_greaterThanOrEqualSelector); 265 | break; 266 | default: 267 | break; 268 | } 269 | 270 | if (_searchRequest.Query == null) 271 | { 272 | _searchRequest.Query = queryContainer; 273 | } 274 | else 275 | { 276 | if (AndCondition) 277 | { 278 | _searchRequest.Query = _searchRequest.Query && _searchRequest.Query; 279 | } 280 | else 281 | { 282 | _searchRequest.Query = _searchRequest.Query || _searchRequest.Query; 283 | } 284 | } 285 | } 286 | 287 | private void SetOrderBy() 288 | { 289 | if (fieldsOrderBy.Any()) 290 | { 291 | fieldsOrderBy.Reverse(); 292 | var _sortList = new List(); 293 | foreach (var item in fieldsOrderBy) 294 | { 295 | _sortList.Add(new FieldSort() 296 | { 297 | Field = item.Field, 298 | Order = item.Order 299 | }); 300 | } 301 | 302 | _searchRequest.Sort = _sortList; 303 | } 304 | } 305 | 306 | internal QueryTranslateResult Translate(Expression expression, Type elementType) 307 | { 308 | this.elementType = elementType; 309 | var queryMap = ElasticQueryMapper.GetMap(this.elementType); 310 | var _index = Indices.Index(queryMap.Index); 311 | 312 | _searchRequest = new SearchRequest(_index); 313 | 314 | if (expression is ConstantExpression == false) 315 | this.Visit(expression); 316 | 317 | _searchRequest.Human = true; 318 | if (_searchRequest.Query == null) 319 | _searchRequest.Query = Query.MatchAll(); 320 | 321 | SetOrderBy(); 322 | 323 | if (returnNumberOfRows) 324 | { 325 | //_searchRequest. 326 | } 327 | 328 | var result = new QueryTranslateResult(_searchRequest, fieldsGroupBy, aggregations, returnNumberOfRows); 329 | 330 | return result; 331 | } 332 | 333 | protected override Expression VisitMethodCall(MethodCallExpression m) 334 | { 335 | 336 | switch (m.Method.Name) 337 | { 338 | case "Where": 339 | LambdaExpression lambda = (LambdaExpression)ExpressionHelper.StripQuotes(m.Arguments[1]); 340 | 341 | this.Visit(lambda.Body); 342 | 343 | return m; 344 | case "Count": 345 | 346 | if (m.Arguments.Count == 1) 347 | { 348 | if (m.Arguments[0] is MethodCallExpression) 349 | { 350 | Visit(m.Arguments[0]); 351 | } 352 | _searchRequest.From = 0; 353 | _searchRequest.Size = 0; 354 | returnNumberOfRows = true; 355 | } 356 | else 357 | { 358 | var countAggLambda = (LambdaExpression)ExpressionHelper.StripQuotes(m.Arguments[1]); 359 | if (countAggLambda.Body is MemberExpression) 360 | { 361 | var memberExp = countAggLambda.Body as MemberExpression; 362 | aggregations.Add(new Aggregation(memberExp.Member.Name.ToCamelCase(), m.Method.Name)); 363 | } 364 | SetAggregation(); 365 | } 366 | return m; 367 | 368 | break; 369 | case "Min": 370 | case "Max": 371 | case "Sum": 372 | case "Average": 373 | var aggLambda = (LambdaExpression)ExpressionHelper.StripQuotes(m.Arguments[1]); 374 | if (aggLambda.Body is MemberExpression) 375 | { 376 | var memberExp = aggLambda.Body as MemberExpression; 377 | aggregations.Add(new Aggregation(memberExp.Member.Name.ToCamelCase(), m.Method.Name)); 378 | } 379 | SetAggregation(); 380 | return m; 381 | break; 382 | case "Contains": 383 | operacao = m.Method.Name; 384 | 385 | var memberContainsExp = (m.Object as MemberExpression); 386 | 387 | if (memberContainsExp != null) 388 | { 389 | if (memberContainsExp.Expression is ConstantExpression) 390 | { 391 | var constMemberExp = memberContainsExp.Expression as ConstantExpression; 392 | var constMemberLambdaExp = Expression.Lambda(constMemberExp).Compile(); 393 | var constMemberExpValue = constMemberLambdaExp.DynamicInvoke(); 394 | var resultConstMemberExpValue = constMemberExpValue.GetType().GetField(memberContainsExp.Member.Name).GetValue(constMemberExpValue); 395 | 396 | if (typeof(System.Collections.IEnumerable).IsAssignableFrom(resultConstMemberExpValue.GetType())) 397 | { 398 | value = resultConstMemberExpValue;//Convert.ChangeType(resultConstMemberExpValue, resultConstMemberExpValue.GetType()); 399 | field = (m.Arguments.First() as MemberExpression)?.Member.Name.ToCamelCase(); 400 | binaryExpType = ExpressionType.Equal;//To make a terms query 401 | SetQuery(); 402 | } 403 | else 404 | { 405 | field = memberContainsExp.Member.Name.ToCamelCase(); 406 | if (m.Arguments[0] is ConstantExpression) 407 | value = (m.Arguments[0] as ConstantExpression).Value; 408 | SetTextSearch(); 409 | } 410 | } 411 | else 412 | { 413 | field = memberContainsExp.Member.Name.ToCamelCase(); 414 | if (m.Arguments[0] is ConstantExpression) 415 | value = (m.Arguments[0] as ConstantExpression).Value; 416 | SetTextSearch(); 417 | } 418 | } 419 | return m; 420 | case "StartsWith": 421 | case "EndsWith": 422 | operacao = m.Method.Name; 423 | field = (m.Object as System.Linq.Expressions.MemberExpression).Member.Name.ToCamelCase(); 424 | 425 | if (m.Arguments[0] is ConstantExpression) 426 | value = (m.Arguments[0] as ConstantExpression).Value; 427 | 428 | SetTextSearch(); 429 | 430 | return m; 431 | break; 432 | case "MatchPhrase": 433 | operacao = m.Method.Name; 434 | field = (m.Arguments[0] as System.Linq.Expressions.MemberExpression).Member.Name.ToCamelCase(); 435 | 436 | if (m.Arguments[1] is ConstantExpression) 437 | value = (m.Arguments[1] as ConstantExpression).Value; 438 | 439 | SetTextSearch(); 440 | 441 | return m; 442 | break; 443 | case "Exists": 444 | 445 | var mExpExists = ((ExpressionHelper.StripQuotes(m.Arguments[1]) as LambdaExpression).Body as MemberExpression).Member.Name.ToCamelCase(); 446 | queryContainer = Query.Exists(f => f.Field(mExpExists)); 447 | 448 | if (_searchRequest.Query == null) 449 | { 450 | _searchRequest.Query = queryContainer; 451 | } 452 | else 453 | { 454 | if (AndCondition) 455 | { 456 | _searchRequest.Query = _searchRequest.Query && _searchRequest.Query; 457 | } 458 | else 459 | { 460 | _searchRequest.Query = _searchRequest.Query || _searchRequest.Query; 461 | } 462 | } 463 | return m; 464 | break; 465 | case "MultiMatch": 466 | operacao = m.Method.Name; 467 | 468 | var fields = (m.Arguments[2] as NewArrayExpression); 469 | 470 | foreach (var item in fields.Expressions) 471 | { 472 | var itemMbExp = (ExpressionHelper.StripQuotes(item) as LambdaExpression).Body as MemberExpression; 473 | if (string.IsNullOrWhiteSpace(field)) 474 | { 475 | field = itemMbExp.Member.Name.ToCamelCase(); 476 | } 477 | else 478 | { 479 | field = field + ";" + itemMbExp.Member.Name.ToCamelCase(); 480 | } 481 | } 482 | 483 | if (m.Arguments[1] is ConstantExpression) 484 | value = (m.Arguments[1] as ConstantExpression).Value; 485 | 486 | SetTextSearch(); 487 | 488 | return m; 489 | break; 490 | case "GroupBy": 491 | 492 | LambdaExpression groupByLambda = (LambdaExpression)ExpressionHelper.StripQuotes(m.Arguments[1]); 493 | if (groupByLambda.Body is NewExpression) 494 | { 495 | var newExp = groupByLambda.Body as NewExpression; 496 | 497 | foreach (var item in newExp.Members) 498 | { 499 | var pInfo = item as PropertyInfo; 500 | fieldsGroupBy.Add(new GroupBy(item.Name.ToCamelCase(), pInfo.PropertyType)); 501 | } 502 | } 503 | else if (groupByLambda.Body is MemberExpression) 504 | { 505 | var memberExp = groupByLambda.Body as MemberExpression; 506 | fieldsGroupBy.Add(new GroupBy(memberExp.Member.Name.ToCamelCase(), groupByLambda.Body.Type)); 507 | } 508 | 509 | SetAggregation(); 510 | 511 | return m; 512 | break; 513 | case "Select": 514 | LambdaExpression selectLambda = (LambdaExpression)ExpressionHelper.StripQuotes(m.Arguments[1]); 515 | if (m.Arguments[0] is MethodCallExpression) 516 | { 517 | var sMExp = m.Arguments[0] as MethodCallExpression; 518 | if (sMExp.Method.Name == "GroupBy") 519 | { 520 | if (selectLambda.Body is NewExpression) 521 | { 522 | var sBodyNewExp = selectLambda.Body as NewExpression; 523 | 524 | foreach (var argument in sBodyNewExp.Arguments) 525 | { 526 | if (argument is MethodCallExpression) 527 | { 528 | var arMExp = argument as MethodCallExpression; 529 | var propArgLambda = (LambdaExpression)ExpressionHelper.StripQuotes(arMExp.Arguments[1]); 530 | var propArgMExp = propArgLambda.Body as MemberExpression; 531 | aggregations.Add(new Aggregation(propArgMExp.Member.Name.ToCamelCase(), arMExp.Method.Name)); 532 | } 533 | } 534 | } 535 | } 536 | } 537 | 538 | this.Visit(m.Arguments[0]); 539 | return m; 540 | break; 541 | case "Take": 542 | 543 | int? _take = null; 544 | if (m.Arguments.Last() is ConstantExpression) 545 | { 546 | var constExp = m.Arguments.Last() as ConstantExpression; 547 | _take = constExp.Value as int?; 548 | } 549 | 550 | _searchRequest.Size = _take; 551 | 552 | if (m.Arguments.First() is ConstantExpression == false) 553 | { 554 | Visit(m.Arguments.First()); 555 | } 556 | 557 | return m; 558 | break; 559 | case "Skip": 560 | 561 | int? _from = null; 562 | if (m.Arguments.Last() is ConstantExpression) 563 | { 564 | var constExp = m.Arguments.Last() as ConstantExpression; 565 | _from = constExp.Value as int?; 566 | } 567 | 568 | _searchRequest.From = _from; 569 | 570 | if (m.Arguments.First() is ConstantExpression == false) 571 | Visit(m.Arguments.First()); 572 | 573 | return m; 574 | break; 575 | case "OrderBy": 576 | case "OrderByDescending": 577 | case "ThenBy": 578 | case "ThenByDescending": 579 | 580 | var orderLambdaExp = (LambdaExpression)ExpressionHelper.StripQuotes(m.Arguments.Last()); 581 | if (orderLambdaExp.Body is MemberExpression) 582 | { 583 | var mExp = orderLambdaExp.Body as MemberExpression; 584 | 585 | fieldsOrderBy.Add(new OrderBy(mExp.Member.Name.ToCamelCase(), (m.Method.Name == "OrderBy" || m.Method.Name == "ThenBy") ? SortOrder.Ascending : SortOrder.Descending)); 586 | } 587 | 588 | if (m.Arguments.First() is ConstantExpression == false) 589 | Visit(m.Arguments.First()); 590 | 591 | return m; 592 | break; 593 | 594 | default: 595 | throw new NotSupportedException(string.Format("The method '{0}' is not supported", m.Method.Name)); 596 | break; 597 | } 598 | } 599 | 600 | protected override Expression VisitUnary(UnaryExpression u) 601 | { 602 | denyCondition = false; 603 | switch (u.NodeType) 604 | { 605 | case ExpressionType.Not: 606 | { 607 | denyCondition = true; 608 | this.Visit(u.Operand); 609 | } 610 | break; 611 | default: 612 | throw new NotSupportedException(string.Format("The unary operator '{0}' is not supported", u.NodeType)); 613 | } 614 | return u; 615 | } 616 | 617 | protected override Expression VisitBinary(BinaryExpression b) 618 | { 619 | this.Visit(b.Left); 620 | 621 | switch (b.NodeType) 622 | { 623 | case ExpressionType.And: 624 | AndCondition = true; 625 | break; 626 | case ExpressionType.Or: 627 | AndCondition = false; 628 | break; 629 | case ExpressionType.Equal: 630 | case ExpressionType.NotEqual: 631 | case ExpressionType.LessThan: 632 | case ExpressionType.LessThanOrEqual: 633 | case ExpressionType.GreaterThan: 634 | case ExpressionType.GreaterThanOrEqual: 635 | binaryExpType = b.NodeType; 636 | break; 637 | default: 638 | throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported", b.NodeType)); 639 | } 640 | this.Visit(b.Right); 641 | 642 | SetQuery(); 643 | 644 | return b; 645 | } 646 | 647 | protected override Expression VisitConstant(ConstantExpression c) 648 | { 649 | if (c.Value == null) 650 | { 651 | queryContainer = Query.Term(f => f.Field(field).Value(null)); 652 | } 653 | else 654 | { 655 | switch (Type.GetTypeCode(c.Value.GetType())) 656 | { 657 | case TypeCode.Object: 658 | throw new NotSupportedException(string.Format("The constant for '{0}' is not supported", c.Value)); 659 | default: 660 | value = c.Value; 661 | break; 662 | } 663 | } 664 | 665 | return c; 666 | } 667 | 668 | protected override Expression VisitMember(MemberExpression m) 669 | { 670 | if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter) 671 | { 672 | field = m.Member.Name.ToCamelCase(); 673 | } 674 | else if (m.Expression != null && m.Expression.NodeType == ExpressionType.Constant) 675 | { 676 | value = (m.Member as FieldInfo).GetValue(((m as MemberExpression).Expression as ConstantExpression).Value); 677 | } 678 | else if (m.Expression == null) 679 | { 680 | var field = m.Type.GetField(m.Member.Name); 681 | value = field.GetValue(null); 682 | } 683 | return m; 684 | } 685 | } 686 | 687 | internal class QueryTranslateResult 688 | { 689 | public QueryTranslateResult(SearchRequest searchRequest, IEnumerable groupBy, IEnumerable aggregation, bool returnNumberOfRows) 690 | { 691 | SearchRequest = searchRequest; 692 | GroupBy = groupBy; 693 | Aggregation = aggregation; 694 | ReturnNumberOfRows = returnNumberOfRows; 695 | } 696 | 697 | public SearchRequest SearchRequest { get; private set; } 698 | 699 | public IEnumerable GroupBy { get; private set; } 700 | 701 | public IEnumerable Aggregation { get; private set; } 702 | 703 | public bool ReturnNumberOfRows { get; private set; } 704 | } 705 | 706 | internal class OrderBy 707 | { 708 | public OrderBy(string field, SortOrder order) 709 | { 710 | Field = field; 711 | Order = order; 712 | } 713 | 714 | public string Field { get; set; } 715 | public SortOrder Order { get; set; } 716 | 717 | } 718 | 719 | internal class GroupBy 720 | { 721 | public GroupBy(string field, Type type) 722 | { 723 | Field = field; 724 | PropertyType = type; 725 | } 726 | 727 | public string Field { get; set; } 728 | public Type PropertyType { get; set; } 729 | } 730 | 731 | internal class Aggregation 732 | { 733 | public Aggregation(string field, string method) 734 | { 735 | Field = field; 736 | Method = method; 737 | } 738 | 739 | public string Field { get; set; } 740 | public string Method { get; set; } 741 | 742 | public string AggName => $"{Method}_{Field}"; 743 | } 744 | } 745 | --------------------------------------------------------------------------------