elasticsearch 查询

  • Python代码中动态修改可查询的最大term数
es_url = [{"host": config.get("search_es", "host"), "port": config.get("search_es", "port")}]
es = Elasticsearch(es_url) 
es.indices.put_settings(index="product", body={"index": {"max_result_window": count}})  #count就是要设置最多可以返回的查询条数 默认是10000,如果不设置,直接设定size大于10000,将会报错
  • 查询es所有的items
search_all = es.search(index="product", doc_type="product",
                   body={"size": count, "query": {"match_all": {}}})   # count是自定义的要查询的条数
  • 利用每个产品名称和其他公司中的产品名称做精确匹配
### 'should' 是对字段“主营构成”和“主营产品详细”做'or'的匹配,'must_not'指的是‘不能有’; 'size'设置要查询的数目
search_result = es.search(index="product", doc_type="product",
                       body={"query": {"bool":
                                      {"should": [{"match_phrase": {"主营构成": product_item}},
                                                  {"match_phrase": {"主营产品详细": product_item}}],
                                                   "must_not": {"match_phrase": {"code": code}}}},
                                                   "size": most_like})   
  • term filter查询
search_result2 = es.search(index="product", doc_type="product",
                                       body={"size": 20,
                                             "query": {"constant_score": {"filter": {"terms": {"主营构成": list(related_ind)}}}}})   #返回结果只是有零星几个字眼匹配上了
  • should条件中可以设置至少匹配的项目(如果同时有must条件,则should中的条件可以没有匹配到,但是如果只有should那么就要至少匹配到其中的一项)
GET /forum/article/_search
{
  "query": {
    "bool": {
      "should": [
        { "match": { "title": "java" }},
        { "match": { "title": "elasticsearch"   }},
        { "match": { "title": "hadoop"   }},
        { "match": { "title": "spark"   }}
      ],
      "minimum_should_match": 3 
    }
  }
}
  • 搜索标题中包含java和elasticsearch的blog

搜索结果精准控制的第一步:灵活使用and关键字,如果你是希望所有的搜索关键字都要匹配的,那么就用and,可以实现单纯match query无法实现的效果

GET /forum/article/_search
{
    "query": {
        "match": {
            "title": {
        "query": "java elasticsearch",
        "operator": "and"
           }
        }
    }
}
  • python程序中设置打印es log信息, 便于debug
import logging
logger = logging.getLogger('elasticsearch')
logger.setLevel(logging.WARNING)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容