How to priortize based on range/filter of Elastic Search DSL, such that a list can be filtered, first to show...





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















The relevance of the Applicants needs to sort, based on availability % in the month.
First, the applicants with %availabiliity more than 60% should come and then the applicants with %availability less than 60% should come.



The Fluent DSL query using ElasticSearch.net which I am trying with



var response = await 
_elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(s =>
s.Aggregations(a => a

.Filter("higer_average", f => f.Filter(fd => fd.Range(r => r.Field(p
=> p.AvailablePercentage).GreaterThanOrEquals(60).Boost(5))))

.Filter("lower_average", f => f.Filter(fd => fd.Range(r => r.Field(p
=> p.AvailablePercentage).GreaterThan(0).LessThan(60).Boost(3)))
)));


or



var response = await _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(
s => s
.Query(q => q
.Bool(p =>
p.Must(queryFilter => queryFilter.MatchAll())
.Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThanOrEquals(60)))
.Boost(5)
.Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThan(0).LessThan(60)))
.Boost(1.2)
)));


The applicant's list coming is not as per the logic. They get mixed.



Even If I try to filter to show only values greater than 60, that also does not work










share|improve this question































    0















    The relevance of the Applicants needs to sort, based on availability % in the month.
    First, the applicants with %availabiliity more than 60% should come and then the applicants with %availability less than 60% should come.



    The Fluent DSL query using ElasticSearch.net which I am trying with



    var response = await 
    _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(s =>
    s.Aggregations(a => a

    .Filter("higer_average", f => f.Filter(fd => fd.Range(r => r.Field(p
    => p.AvailablePercentage).GreaterThanOrEquals(60).Boost(5))))

    .Filter("lower_average", f => f.Filter(fd => fd.Range(r => r.Field(p
    => p.AvailablePercentage).GreaterThan(0).LessThan(60).Boost(3)))
    )));


    or



    var response = await _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(
    s => s
    .Query(q => q
    .Bool(p =>
    p.Must(queryFilter => queryFilter.MatchAll())
    .Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThanOrEquals(60)))
    .Boost(5)
    .Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThan(0).LessThan(60)))
    .Boost(1.2)
    )));


    The applicant's list coming is not as per the logic. They get mixed.



    Even If I try to filter to show only values greater than 60, that also does not work










    share|improve this question



























      0












      0








      0


      1






      The relevance of the Applicants needs to sort, based on availability % in the month.
      First, the applicants with %availabiliity more than 60% should come and then the applicants with %availability less than 60% should come.



      The Fluent DSL query using ElasticSearch.net which I am trying with



      var response = await 
      _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(s =>
      s.Aggregations(a => a

      .Filter("higer_average", f => f.Filter(fd => fd.Range(r => r.Field(p
      => p.AvailablePercentage).GreaterThanOrEquals(60).Boost(5))))

      .Filter("lower_average", f => f.Filter(fd => fd.Range(r => r.Field(p
      => p.AvailablePercentage).GreaterThan(0).LessThan(60).Boost(3)))
      )));


      or



      var response = await _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(
      s => s
      .Query(q => q
      .Bool(p =>
      p.Must(queryFilter => queryFilter.MatchAll())
      .Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThanOrEquals(60)))
      .Boost(5)
      .Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThan(0).LessThan(60)))
      .Boost(1.2)
      )));


      The applicant's list coming is not as per the logic. They get mixed.



      Even If I try to filter to show only values greater than 60, that also does not work










      share|improve this question
















      The relevance of the Applicants needs to sort, based on availability % in the month.
      First, the applicants with %availabiliity more than 60% should come and then the applicants with %availability less than 60% should come.



      The Fluent DSL query using ElasticSearch.net which I am trying with



      var response = await 
      _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(s =>
      s.Aggregations(a => a

      .Filter("higer_average", f => f.Filter(fd => fd.Range(r => r.Field(p
      => p.AvailablePercentage).GreaterThanOrEquals(60).Boost(5))))

      .Filter("lower_average", f => f.Filter(fd => fd.Range(r => r.Field(p
      => p.AvailablePercentage).GreaterThan(0).LessThan(60).Boost(3)))
      )));


      or



      var response = await _elasticClient.SearchAsync<ApplicantsWithDetailsResponse>(
      s => s
      .Query(q => q
      .Bool(p =>
      p.Must(queryFilter => queryFilter.MatchAll())
      .Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThanOrEquals(60)))
      .Boost(5)
      .Filter(f => f.Range(r => r.Field("AvailablePercentage").GreaterThan(0).LessThan(60)))
      .Boost(1.2)
      )));


      The applicant's list coming is not as per the logic. They get mixed.



      Even If I try to filter to show only values greater than 60, that also does not work







      c# elasticsearch .net-core nest elasticsearch.net






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 30 at 1:33









      Russ Cam

      105k24170229




      105k24170229










      asked Jan 3 at 10:59









      Himanshu GoyalHimanshu Goyal

      43




      43
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Your query is not correct; it serializes to



          {
          "query": {
          "bool": {
          "boost": 1.2,
          "filter": [
          {
          "range": {
          "AvailablePercentage": {
          "gt": 0.0,
          "lt": 60.0
          }
          }
          }
          ],
          "must": [
          {
          "match_all": {}
          }
          ]
          }
          }
          }



          • the boost is applied to the entire bool query

          • the last Filter assigned overwrites any previous filters

          • Filters are anded, so all would need to be satisfied for a match


          It's useful during development to be observe what JSON the client sends to Elasticsearch. There are numerous ways that you can do this, and one that is useful is



          var defaultIndex = "default-index";
          var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

          var settings = new ConnectionSettings(pool)
          .DefaultIndex(defaultIndex)
          .DisableDirectStreaming()
          .PrettyJson()
          .OnRequestCompleted(callDetails =>
          {
          if (callDetails.RequestBodyInBytes != null)
          {
          Console.WriteLine(
          $"{callDetails.HttpMethod} {callDetails.Uri} n" +
          $"{Encoding.UTF8.GetString(callDetails.RequestBodyInBytes)}");
          }
          else
          {
          Console.WriteLine($"{callDetails.HttpMethod} {callDetails.Uri}");
          }

          Console.WriteLine();

          if (callDetails.ResponseBodyInBytes != null)
          {
          Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
          $"{Encoding.UTF8.GetString(callDetails.ResponseBodyInBytes)}n" +
          $"{new string('-', 30)}n");
          }
          else
          {
          Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
          $"{new string('-', 30)}n");
          }
          });

          var client = new ElasticClient(settings);


          This will write all requests and responses out to the Console. Note that you may not want to do this in production for every request, as there is a performance overhead in buffering requests and responses in this way.



          Your query should look something like



          var response = client.Search<ApplicantsWithDetailsResponse>(s => s
          .Query(q => q
          .Bool(p => p
          .Must(queryFilter => queryFilter
          .MatchAll()
          )
          .Should(f => f
          .Range(r => r
          .Field("AvailablePercentage")
          .GreaterThanOrEquals(60)
          .Boost(5)
          ), f => f
          .Range(r => r
          .Field("AvailablePercentage")
          .GreaterThan(0)
          .LessThan(60)
          .Boost(1.2)
          )
          )
          .MinimumShouldMatch(1)
          )
          )
          );


          Which emits the following query



          {
          "query": {
          "bool": {
          "minimum_should_match": 1,
          "must": [
          {
          "match_all": {}
          }
          ],
          "should": [
          {
          "range": {
          "AvailablePercentage": {
          "boost": 5.0,
          "gte": 60.0
          }
          }
          },
          {
          "range": {
          "AvailablePercentage": {
          "boost": 1.2,
          "gt": 0.0,
          "lt": 60.0
          }
          }
          }
          ]
          }
          }
          }


          Combine range queries with should clauses and specify that at least one must match using MinimumShouldMatch. This is needed because of the presence of a must clause, which means that the should clauses act as boosting signal to documents, but a document does not have to satisfy any of the clauses to be considered a match. With MinimumShouldMatch set to 1, at least one of the should clauses has to be satisfied to be considered a match.



          Since the must clause is a match_all query in this case, we could simply omit it and remove MinimumShouldMatch. A should clause without a must clause implies that at least one of the clauses must match.



          We can also combine queries using operator overloading, for brevity. The final query would look like



          var response = client.Search<ApplicantsWithDetailsResponse>(s => s
          .Query(q => q
          .Range(r => r
          .Field("AvailablePercentage")
          .GreaterThanOrEquals(60)
          .Boost(5)
          ) || q
          .Range(r => r
          .Field("AvailablePercentage")
          .GreaterThan(0)
          .LessThan(60)
          .Boost(1.2)
          )
          )
          );


          which emits the query



          {
          "query": {
          "bool": {
          "should": [
          {
          "range": {
          "AvailablePercentage": {
          "boost": 5.0,
          "gte": 60.0
          }
          }
          },
          {
          "range": {
          "AvailablePercentage": {
          "boost": 1.2,
          "gt": 0.0,
          "lt": 60.0
          }
          }
          }
          ]
          }
          }
          }





          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54020984%2fhow-to-priortize-based-on-range-filter-of-elastic-search-dsl-such-that-a-list-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Your query is not correct; it serializes to



            {
            "query": {
            "bool": {
            "boost": 1.2,
            "filter": [
            {
            "range": {
            "AvailablePercentage": {
            "gt": 0.0,
            "lt": 60.0
            }
            }
            }
            ],
            "must": [
            {
            "match_all": {}
            }
            ]
            }
            }
            }



            • the boost is applied to the entire bool query

            • the last Filter assigned overwrites any previous filters

            • Filters are anded, so all would need to be satisfied for a match


            It's useful during development to be observe what JSON the client sends to Elasticsearch. There are numerous ways that you can do this, and one that is useful is



            var defaultIndex = "default-index";
            var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            var settings = new ConnectionSettings(pool)
            .DefaultIndex(defaultIndex)
            .DisableDirectStreaming()
            .PrettyJson()
            .OnRequestCompleted(callDetails =>
            {
            if (callDetails.RequestBodyInBytes != null)
            {
            Console.WriteLine(
            $"{callDetails.HttpMethod} {callDetails.Uri} n" +
            $"{Encoding.UTF8.GetString(callDetails.RequestBodyInBytes)}");
            }
            else
            {
            Console.WriteLine($"{callDetails.HttpMethod} {callDetails.Uri}");
            }

            Console.WriteLine();

            if (callDetails.ResponseBodyInBytes != null)
            {
            Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
            $"{Encoding.UTF8.GetString(callDetails.ResponseBodyInBytes)}n" +
            $"{new string('-', 30)}n");
            }
            else
            {
            Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
            $"{new string('-', 30)}n");
            }
            });

            var client = new ElasticClient(settings);


            This will write all requests and responses out to the Console. Note that you may not want to do this in production for every request, as there is a performance overhead in buffering requests and responses in this way.



            Your query should look something like



            var response = client.Search<ApplicantsWithDetailsResponse>(s => s
            .Query(q => q
            .Bool(p => p
            .Must(queryFilter => queryFilter
            .MatchAll()
            )
            .Should(f => f
            .Range(r => r
            .Field("AvailablePercentage")
            .GreaterThanOrEquals(60)
            .Boost(5)
            ), f => f
            .Range(r => r
            .Field("AvailablePercentage")
            .GreaterThan(0)
            .LessThan(60)
            .Boost(1.2)
            )
            )
            .MinimumShouldMatch(1)
            )
            )
            );


            Which emits the following query



            {
            "query": {
            "bool": {
            "minimum_should_match": 1,
            "must": [
            {
            "match_all": {}
            }
            ],
            "should": [
            {
            "range": {
            "AvailablePercentage": {
            "boost": 5.0,
            "gte": 60.0
            }
            }
            },
            {
            "range": {
            "AvailablePercentage": {
            "boost": 1.2,
            "gt": 0.0,
            "lt": 60.0
            }
            }
            }
            ]
            }
            }
            }


            Combine range queries with should clauses and specify that at least one must match using MinimumShouldMatch. This is needed because of the presence of a must clause, which means that the should clauses act as boosting signal to documents, but a document does not have to satisfy any of the clauses to be considered a match. With MinimumShouldMatch set to 1, at least one of the should clauses has to be satisfied to be considered a match.



            Since the must clause is a match_all query in this case, we could simply omit it and remove MinimumShouldMatch. A should clause without a must clause implies that at least one of the clauses must match.



            We can also combine queries using operator overloading, for brevity. The final query would look like



            var response = client.Search<ApplicantsWithDetailsResponse>(s => s
            .Query(q => q
            .Range(r => r
            .Field("AvailablePercentage")
            .GreaterThanOrEquals(60)
            .Boost(5)
            ) || q
            .Range(r => r
            .Field("AvailablePercentage")
            .GreaterThan(0)
            .LessThan(60)
            .Boost(1.2)
            )
            )
            );


            which emits the query



            {
            "query": {
            "bool": {
            "should": [
            {
            "range": {
            "AvailablePercentage": {
            "boost": 5.0,
            "gte": 60.0
            }
            }
            },
            {
            "range": {
            "AvailablePercentage": {
            "boost": 1.2,
            "gt": 0.0,
            "lt": 60.0
            }
            }
            }
            ]
            }
            }
            }





            share|improve this answer






























              0














              Your query is not correct; it serializes to



              {
              "query": {
              "bool": {
              "boost": 1.2,
              "filter": [
              {
              "range": {
              "AvailablePercentage": {
              "gt": 0.0,
              "lt": 60.0
              }
              }
              }
              ],
              "must": [
              {
              "match_all": {}
              }
              ]
              }
              }
              }



              • the boost is applied to the entire bool query

              • the last Filter assigned overwrites any previous filters

              • Filters are anded, so all would need to be satisfied for a match


              It's useful during development to be observe what JSON the client sends to Elasticsearch. There are numerous ways that you can do this, and one that is useful is



              var defaultIndex = "default-index";
              var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

              var settings = new ConnectionSettings(pool)
              .DefaultIndex(defaultIndex)
              .DisableDirectStreaming()
              .PrettyJson()
              .OnRequestCompleted(callDetails =>
              {
              if (callDetails.RequestBodyInBytes != null)
              {
              Console.WriteLine(
              $"{callDetails.HttpMethod} {callDetails.Uri} n" +
              $"{Encoding.UTF8.GetString(callDetails.RequestBodyInBytes)}");
              }
              else
              {
              Console.WriteLine($"{callDetails.HttpMethod} {callDetails.Uri}");
              }

              Console.WriteLine();

              if (callDetails.ResponseBodyInBytes != null)
              {
              Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
              $"{Encoding.UTF8.GetString(callDetails.ResponseBodyInBytes)}n" +
              $"{new string('-', 30)}n");
              }
              else
              {
              Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
              $"{new string('-', 30)}n");
              }
              });

              var client = new ElasticClient(settings);


              This will write all requests and responses out to the Console. Note that you may not want to do this in production for every request, as there is a performance overhead in buffering requests and responses in this way.



              Your query should look something like



              var response = client.Search<ApplicantsWithDetailsResponse>(s => s
              .Query(q => q
              .Bool(p => p
              .Must(queryFilter => queryFilter
              .MatchAll()
              )
              .Should(f => f
              .Range(r => r
              .Field("AvailablePercentage")
              .GreaterThanOrEquals(60)
              .Boost(5)
              ), f => f
              .Range(r => r
              .Field("AvailablePercentage")
              .GreaterThan(0)
              .LessThan(60)
              .Boost(1.2)
              )
              )
              .MinimumShouldMatch(1)
              )
              )
              );


              Which emits the following query



              {
              "query": {
              "bool": {
              "minimum_should_match": 1,
              "must": [
              {
              "match_all": {}
              }
              ],
              "should": [
              {
              "range": {
              "AvailablePercentage": {
              "boost": 5.0,
              "gte": 60.0
              }
              }
              },
              {
              "range": {
              "AvailablePercentage": {
              "boost": 1.2,
              "gt": 0.0,
              "lt": 60.0
              }
              }
              }
              ]
              }
              }
              }


              Combine range queries with should clauses and specify that at least one must match using MinimumShouldMatch. This is needed because of the presence of a must clause, which means that the should clauses act as boosting signal to documents, but a document does not have to satisfy any of the clauses to be considered a match. With MinimumShouldMatch set to 1, at least one of the should clauses has to be satisfied to be considered a match.



              Since the must clause is a match_all query in this case, we could simply omit it and remove MinimumShouldMatch. A should clause without a must clause implies that at least one of the clauses must match.



              We can also combine queries using operator overloading, for brevity. The final query would look like



              var response = client.Search<ApplicantsWithDetailsResponse>(s => s
              .Query(q => q
              .Range(r => r
              .Field("AvailablePercentage")
              .GreaterThanOrEquals(60)
              .Boost(5)
              ) || q
              .Range(r => r
              .Field("AvailablePercentage")
              .GreaterThan(0)
              .LessThan(60)
              .Boost(1.2)
              )
              )
              );


              which emits the query



              {
              "query": {
              "bool": {
              "should": [
              {
              "range": {
              "AvailablePercentage": {
              "boost": 5.0,
              "gte": 60.0
              }
              }
              },
              {
              "range": {
              "AvailablePercentage": {
              "boost": 1.2,
              "gt": 0.0,
              "lt": 60.0
              }
              }
              }
              ]
              }
              }
              }





              share|improve this answer




























                0












                0








                0







                Your query is not correct; it serializes to



                {
                "query": {
                "bool": {
                "boost": 1.2,
                "filter": [
                {
                "range": {
                "AvailablePercentage": {
                "gt": 0.0,
                "lt": 60.0
                }
                }
                }
                ],
                "must": [
                {
                "match_all": {}
                }
                ]
                }
                }
                }



                • the boost is applied to the entire bool query

                • the last Filter assigned overwrites any previous filters

                • Filters are anded, so all would need to be satisfied for a match


                It's useful during development to be observe what JSON the client sends to Elasticsearch. There are numerous ways that you can do this, and one that is useful is



                var defaultIndex = "default-index";
                var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

                var settings = new ConnectionSettings(pool)
                .DefaultIndex(defaultIndex)
                .DisableDirectStreaming()
                .PrettyJson()
                .OnRequestCompleted(callDetails =>
                {
                if (callDetails.RequestBodyInBytes != null)
                {
                Console.WriteLine(
                $"{callDetails.HttpMethod} {callDetails.Uri} n" +
                $"{Encoding.UTF8.GetString(callDetails.RequestBodyInBytes)}");
                }
                else
                {
                Console.WriteLine($"{callDetails.HttpMethod} {callDetails.Uri}");
                }

                Console.WriteLine();

                if (callDetails.ResponseBodyInBytes != null)
                {
                Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
                $"{Encoding.UTF8.GetString(callDetails.ResponseBodyInBytes)}n" +
                $"{new string('-', 30)}n");
                }
                else
                {
                Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
                $"{new string('-', 30)}n");
                }
                });

                var client = new ElasticClient(settings);


                This will write all requests and responses out to the Console. Note that you may not want to do this in production for every request, as there is a performance overhead in buffering requests and responses in this way.



                Your query should look something like



                var response = client.Search<ApplicantsWithDetailsResponse>(s => s
                .Query(q => q
                .Bool(p => p
                .Must(queryFilter => queryFilter
                .MatchAll()
                )
                .Should(f => f
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThanOrEquals(60)
                .Boost(5)
                ), f => f
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThan(0)
                .LessThan(60)
                .Boost(1.2)
                )
                )
                .MinimumShouldMatch(1)
                )
                )
                );


                Which emits the following query



                {
                "query": {
                "bool": {
                "minimum_should_match": 1,
                "must": [
                {
                "match_all": {}
                }
                ],
                "should": [
                {
                "range": {
                "AvailablePercentage": {
                "boost": 5.0,
                "gte": 60.0
                }
                }
                },
                {
                "range": {
                "AvailablePercentage": {
                "boost": 1.2,
                "gt": 0.0,
                "lt": 60.0
                }
                }
                }
                ]
                }
                }
                }


                Combine range queries with should clauses and specify that at least one must match using MinimumShouldMatch. This is needed because of the presence of a must clause, which means that the should clauses act as boosting signal to documents, but a document does not have to satisfy any of the clauses to be considered a match. With MinimumShouldMatch set to 1, at least one of the should clauses has to be satisfied to be considered a match.



                Since the must clause is a match_all query in this case, we could simply omit it and remove MinimumShouldMatch. A should clause without a must clause implies that at least one of the clauses must match.



                We can also combine queries using operator overloading, for brevity. The final query would look like



                var response = client.Search<ApplicantsWithDetailsResponse>(s => s
                .Query(q => q
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThanOrEquals(60)
                .Boost(5)
                ) || q
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThan(0)
                .LessThan(60)
                .Boost(1.2)
                )
                )
                );


                which emits the query



                {
                "query": {
                "bool": {
                "should": [
                {
                "range": {
                "AvailablePercentage": {
                "boost": 5.0,
                "gte": 60.0
                }
                }
                },
                {
                "range": {
                "AvailablePercentage": {
                "boost": 1.2,
                "gt": 0.0,
                "lt": 60.0
                }
                }
                }
                ]
                }
                }
                }





                share|improve this answer















                Your query is not correct; it serializes to



                {
                "query": {
                "bool": {
                "boost": 1.2,
                "filter": [
                {
                "range": {
                "AvailablePercentage": {
                "gt": 0.0,
                "lt": 60.0
                }
                }
                }
                ],
                "must": [
                {
                "match_all": {}
                }
                ]
                }
                }
                }



                • the boost is applied to the entire bool query

                • the last Filter assigned overwrites any previous filters

                • Filters are anded, so all would need to be satisfied for a match


                It's useful during development to be observe what JSON the client sends to Elasticsearch. There are numerous ways that you can do this, and one that is useful is



                var defaultIndex = "default-index";
                var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

                var settings = new ConnectionSettings(pool)
                .DefaultIndex(defaultIndex)
                .DisableDirectStreaming()
                .PrettyJson()
                .OnRequestCompleted(callDetails =>
                {
                if (callDetails.RequestBodyInBytes != null)
                {
                Console.WriteLine(
                $"{callDetails.HttpMethod} {callDetails.Uri} n" +
                $"{Encoding.UTF8.GetString(callDetails.RequestBodyInBytes)}");
                }
                else
                {
                Console.WriteLine($"{callDetails.HttpMethod} {callDetails.Uri}");
                }

                Console.WriteLine();

                if (callDetails.ResponseBodyInBytes != null)
                {
                Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
                $"{Encoding.UTF8.GetString(callDetails.ResponseBodyInBytes)}n" +
                $"{new string('-', 30)}n");
                }
                else
                {
                Console.WriteLine($"Status: {callDetails.HttpStatusCode}n" +
                $"{new string('-', 30)}n");
                }
                });

                var client = new ElasticClient(settings);


                This will write all requests and responses out to the Console. Note that you may not want to do this in production for every request, as there is a performance overhead in buffering requests and responses in this way.



                Your query should look something like



                var response = client.Search<ApplicantsWithDetailsResponse>(s => s
                .Query(q => q
                .Bool(p => p
                .Must(queryFilter => queryFilter
                .MatchAll()
                )
                .Should(f => f
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThanOrEquals(60)
                .Boost(5)
                ), f => f
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThan(0)
                .LessThan(60)
                .Boost(1.2)
                )
                )
                .MinimumShouldMatch(1)
                )
                )
                );


                Which emits the following query



                {
                "query": {
                "bool": {
                "minimum_should_match": 1,
                "must": [
                {
                "match_all": {}
                }
                ],
                "should": [
                {
                "range": {
                "AvailablePercentage": {
                "boost": 5.0,
                "gte": 60.0
                }
                }
                },
                {
                "range": {
                "AvailablePercentage": {
                "boost": 1.2,
                "gt": 0.0,
                "lt": 60.0
                }
                }
                }
                ]
                }
                }
                }


                Combine range queries with should clauses and specify that at least one must match using MinimumShouldMatch. This is needed because of the presence of a must clause, which means that the should clauses act as boosting signal to documents, but a document does not have to satisfy any of the clauses to be considered a match. With MinimumShouldMatch set to 1, at least one of the should clauses has to be satisfied to be considered a match.



                Since the must clause is a match_all query in this case, we could simply omit it and remove MinimumShouldMatch. A should clause without a must clause implies that at least one of the clauses must match.



                We can also combine queries using operator overloading, for brevity. The final query would look like



                var response = client.Search<ApplicantsWithDetailsResponse>(s => s
                .Query(q => q
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThanOrEquals(60)
                .Boost(5)
                ) || q
                .Range(r => r
                .Field("AvailablePercentage")
                .GreaterThan(0)
                .LessThan(60)
                .Boost(1.2)
                )
                )
                );


                which emits the query



                {
                "query": {
                "bool": {
                "should": [
                {
                "range": {
                "AvailablePercentage": {
                "boost": 5.0,
                "gte": 60.0
                }
                }
                },
                {
                "range": {
                "AvailablePercentage": {
                "boost": 1.2,
                "gt": 0.0,
                "lt": 60.0
                }
                }
                }
                ]
                }
                }
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 30 at 1:37

























                answered Jan 29 at 21:17









                Russ CamRuss Cam

                105k24170229




                105k24170229
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54020984%2fhow-to-priortize-based-on-range-filter-of-elastic-search-dsl-such-that-a-list-c%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    Npm cannot find a required file even through it is in the searched directory