草庐IT

Elasticsearch使用篇 - 查询排序

等後那场雪 2023-04-04 原文

前言

Elasticsearch 查询默认按照分值由大到小进行排序。

分值计算基于 BM25 算法。

Elasticsearch排序

影响排序的方式

可以使用 boost 对字段加权,从而影响排序结果。

GET kibana_sample_data_logs/_search
{
	"track_total_hits": true,
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "message": {
              "query": "elasticsearch",
              "boost": 2
            }
          }
        },
        {
          "match": {
            "message": {
              "query": "beats",
              "boost": 1
            }
          }
        }
      ]
    }
  }
}

可以使用 script_score 查询指定分值,从而影响排序结果

GET kibana_sample_data_logs/_search
{
  "track_total_hits": true,
  "query": {
    "script_score": {
      "query": {
        "match": {
          "message": "elasticsearch"
        }
      },
      "script": {
        "source": """
          _score * 2
        """
      }
    }
  }
}

sort排序

对指定字段进行排序,对应的 doc_values 参数需要设置为 true。而 doc_values 参数在创建索引时,默认为 true,即启用。如果字段不需要排序,可以设置为 false。值得注意的是,text 类型的字段对应的 doc_values 参数默认为 false。

PUT kibana_sample_data_logs_values
{
  "mappings": {
    "properties": {
      "bytes": {
        "type": "integer",
        "doc_values": false
      }
    }
  }
}

POST _reindex
{
  "source": {
    "index": "kibana_sample_data_logs"
  },
  "dest": {
    "index": "kibana_sample_data_logs_values"
  }
}

GET kibana_sample_data_logs_values/_search
{
	"track_total_hits": true,
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "message": {
              "query": "elasticsearch"
            }
          }
        }
      ]
    }
  },
  "sort": [
    {
      "bytes": {
        "order": "desc"
      }
    }
  ]
}

上述查询会抛出异常。

sort 支持多字段排序。先按照第一个字段排序,然后按照下一个字段排序。

GET kibana_sample_data_logs/_search
{
  "track_total_hits": true, 
  "sort": [
    {
      "timestamp": {
        "order": "desc"
      }
    },
    {
      "response.keyword": {
        "order": "desc"
      }
    },
    {
      "bytes": {
        "order": "desc"
      }
    },
    "_score"
  ]
}
  • track_scores:指定是否追踪评分。默认 false,即在使用 sort 排序时,默认不计算评分。

  • order:排序规则,支持 ascdesc。如果基于 _score 排序,则默认的排序规则是 desc;否则默认的排序规则是 asc

  • mode:排序模式。对于数组或者多值字段,选取哪个值参与排序。如果排序规则是 asc,则默认的排序模式是 min;如果排序规则是 desc,则默认的排序模式是 max

    • min:选取最小值。
    • max:选取最大值。
    • sum:取所有值的和。仅应用于数值类型的数组字段。
    • avg:取所有值的平均值。仅应用于数值类型的数组字段。
    • median:取所有值的中间值。仅引用于数值类型的数组字段。
GET kibana_sample_data_ecommerce/_search
{
  "sort": [
    {
      "products.base_price": {
        "order": "desc",
        "mode": "min"
      }
    }
  ]
}
  • unmapped_type:如果索引中指定字段的映射不存在时,指定一个数据类型,然后排序时对它进行忽略。

  • missing:如果用于排序的字段的值不存在,指定一个缺省值。支持 _last_first 或者自定义值。默认是 _last

PUT demo1
{
  "mappings": {
    "properties": {
      "cardId": {
        "type": "integer"
      }
    }
  }
}

PUT demo2
{
  "mappings": {
    "properties": {
      "name": {
        "type": "keyword"
      }
    }
  }
}

PUT demo1/_doc/1
{
  "cardId": 6
}

PUT demo2/_doc/1
{
  "name": "Tom"
}

GET demo1,demo2/_search
{
  "sort": [
    {
      "cardId": {
        "order": "asc",
        "unmapped_type": "integer",
        "missing": "_first"
      }
    }
  ]
}
  • numeric_type:对于数值类型的字段,可以强制转换为指定类型的字段。支持 doublelongdatedate_nanos。 可以用于跨索引的不同数据类型的字段的排序。

PUT index_double
{
  "mappings": {
    "properties": {
      "amount": {
        "type": "double"
      }
    }
  }
}

PUT index_long
{
  "mappings": {
    "properties": {
      "amount": {
        "type": "long"
      }
    }
  }
}

GET index_long,index_double/_search
{
  "sort": [
    {
      "amount": {
        "order": "desc",
        "numeric_type": "double"
      }
    }
  ]
}

sort 支持 script 脚本方式自定义评分方式,从而影响排序。

GET kibana_sample_data_ecommerce/_search
{
  "track_scores": true,
  "sort": [
    {
      "_script": {
        "type": "number",
        "script": {
          "lang": "painless",
          "source": """
            doc['taxful_total_price'].value / doc['total_quantity'].value
          """
        },
        "order": "desc"
      }
    }
  ]
}

GET kibana_sample_data_ecommerce/_search
{
  "track_scores": true,
  "sort": [
    {
      "_script": {
        "order": "desc",
        "type": "string",
        "script": {
          "lang": "painless",
          "source": """
            doc['day_of_week'].value
          """
        }
      }
    }
  ]
}

sort 支持对 nested 对象中的字段进行排序。

PUT /sort_demo
{
  "mappings": {
    "dynamic"   : "strict",
    "properties": {
      "parent": {
        "type"      : "nested", 
        "properties": {
          "name" : {"type": "keyword"},
          "age"  : {"type": "long"},
          "child": {
            "type"      : "nested",
            "properties": {
              "num": {"type": "long"}
            }
          }
        }
      }
    }
  }
}

PUT sort_demo/_doc/1
{
  "parent": [
    {
      "name": "hello",
      "age": 18,
      "child": [
        {
          "num": 13
        },
        {
          "num": 14
        },
        {
          "num": 15
        }
      ]
    },
    {
      "name": "hello",
      "age": 20,
      "child": [
        {
          "num": 25
        }
      ]
    },
    {
      "name": "hello",
      "age": 19,
      "child": [
        {
          "num": 10
        }
      ]
    }
  ]
}

PUT sort_demo/_doc/2
{
  "parent": [
    {
      "name": "hello",
      "age": 19,
      "child": [
        {
          "num": 13
        },
        {
          "num": 16
        },
        {
          "num": 15
        }
      ]
    },
    {
      "name": "hello",
      "age": 17,
      "child": [
        {
          "num": 19
        }
      ]
    },
    {
      "name": "hello",
      "age": 19,
      "child": [
        {
          "num": 29
        }
      ]
    }
  ]
}

PUT sort_demo/_doc/3
{
  "parent": [
    {
      "name": "hello",
      "age": 28,
      "child": [
        {
          "num": 13
        },
        {
          "num": 84
        },
        {
          "num": 15
        }
      ]
    },
    {
      "name": "hello",
      "age": 37,
      "child": [
        {
          "num": 99
        }
      ]
    },
    {
      "name": "hello",
      "age": 49,
      "child": [
        {
          "num": 14
        }
      ]
    }
  ]
}

GET sort_demo/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "parent.child.num": {
        "order" : "desc",
        "mode": "max", 
        "nested": {
          "path"  : "parent.child",
          "max_children": 3,
          "filter": {
            "range": {
              "parent.child.num": {
                "lt": 99
              }
            }
          }
        }
      }
    }
  ]
}

GET sort_demo/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "parent.child.num": {
        "order" : "desc",
        "mode": "max", 
        "nested": {
          "path"  : "parent",
          "filter": {
            "range": {
              "parent.age": {
                "lt": 37
              }
            }
          },
          "nested": {
            "path": "parent.child",
            "filter": {
              "range": {
                "parent.child.num": {
                  "lt": 84
                }
              }
            }
          }
        }
      }
    }
  ]
}

rescore 重排序

对 query、post_filter 语句返回的 Top-K 文档重新评分,然后基于前后两次查询结果的分值对这些 Top-K 文档进行重新排序。

Rescoring can help to improve precision by reordering just the top (eg 100 - 500) documents returned by the query and post_filter phases, using a secondary (usually more costly) algorithm, instead of applying the costly algorithm to all documents in the index.

rescore 请求在每个分片返回结果之前执行,由处理搜索请求的节点对结果进行排序。

A rescore request is executed on each shard before it returns its results to be sorted by the node handling the overall search request.

Elasticsearch rescore资料

GET kibana_sample_data_flights_compound/_search
{
  "track_total_hits": true,
  "query": {
    "match": {
      "Dest": {
        "query": "International Airport",
        "operator": "or"
      }
    }
  },
  "rescore": {
    "query": {
      "rescore_query": {
        "match": {
          "Origin": {
            "query": "Seattle"
          }
        }
      },
      "query_weight": 1,
      "rescore_query_weight": 1,
      "score_mode": "max"
    },
    "window_size": 50
  }
}
  • query_weight:原始查询的分值权重,默认 1。
  • rescore_query_weight:二次查询的分值权重,默认 1。
  • score_mode:原始查询的分值与二次查询的分值的组合方式,支持 total、multiply、avg、max、min。默认 total。
  • window_size:Top-K 文档的 K 的值。默认 10。

支持按顺序执行多个 rescore 重排序。

The first one gets the results of the query then the second one gets the results of the first, etc. The second rescore will “see” the sorting done by the first rescore so it is possible to use a large window on the first rescore to pull documents into a smaller window for the second rescore.

GET kibana_sample_data_flights_compound/_search
{
  "track_total_hits": true,
  "query": {
    "match": {
      "Dest": {
        "query": "International Airport",
        "operator": "or"
      }
    }
  },
  "rescore": [
    {
      "query": {
        "rescore_query": {
          "match": {
            "Origin": {
              "query": "Seattle"
            }
          }
        },
        "query_weight": 1,
        "rescore_query_weight": 1,
        "score_mode": "min"
      },
      "window_size": 50
    },
    {
      "query": {
        "rescore_query": {
          "match": {
            "OriginCountry": {
              "query": "IT"
            }
          }
        },
        "score_mode": "max"
      },
      "window_size": 20
    }
  ]
}

rescore 内部也支持 function_score 自定义脚本计算分值并进行二次排序。

GET kibana_sample_data_flights_compound/_search
{
  "track_total_hits": true,
  "query": {
    "match": {
      "Dest": {
        "query": "International Airport",
        "operator": "or"
      }
    }
  },
  "rescore": {
    "query": {
      "rescore_query": {
        "function_score": {
          "script_score": {
            "script": {
              "source": """
                doc['FlightTimeMin'].value/100
              """
            }
          }
        }
      },
      "query_weight": 1,
      "rescore_query_weight": 1,
      "score_mode": "max"
    },
    "window_size": 50
  }
}

创建索引时指定排序规则

Elasticsearch 支持创建索引时指定排序规则,便于之后进行指定的顺序查询。

PUT kibana_sample_data_logs_order
{
  "settings": {
    "index": {
      "sort.field": "timestamp",
      "sort.order": "desc",
      "sort.mode": "max"
    }
  },
  "mappings": {
    "properties": {
      "timestamp": {
        "type": "date"
      }
    }
  }
}

POST _reindex
{
  "source": {
    "index": "kibana_sample_data_logs"
  },
  "dest": {
    "index": "kibana_sample_data_logs_order"
  }
}

所以下面两个查询的结果都是一样的。

GET kibana_sample_data_logs_order/_search
{
  "track_total_hits": true
}

GET kibana_sample_data_logs_order/_search
{
  "track_total_hits": true,
  "sort": [
    {
      "timestamp": {
        "order": "desc"
      }
    }
  ]
}

有关Elasticsearch使用篇 - 查询排序的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐