Elasticsearch结构化搜索

 

查找准确值

 

{
    "query" : {
        "filtered" : { 
            "query" : {
                "match_all" : {} 
            },
            "filter" : {
                "term" : { 
                    "phoneNumber" : "16912132423"
                }
            }
        }
    }
}

 

analyze API分析具体字段的索引方式

_analyze?tokenizer=standard
"value"

_analyze?field=name
"value"

重建索引:

必须首先删除索引,因为我们不能修改已经存在的映射。

curl  -XDELETE  web:9200/my_store

为了避免“所以当我们用 XHDK-A-1293-#fJ3 来查找时,得不到任何结果,因为这个表征不在我们的倒排索引中”,我们需要通过设置这个字段为 not_analyzed 来告诉 Elasticsearch 它包含一个准确值。

curl  -XPUT  web:9200/my_store -d '{    "mappings" : {        "products" : {           "properties" : {                "productID" : {                    "type" : "string",                    "index" : "not_analyzed"                },"name" : {                    "type" : "string",                   "index" : "not_analyzed"               }            }        }    }}'

 插入数据

curl -XPOST web:9200/my_store/products/1?pretty -d '{"name":"香蕉","productid":"XHDK-A-1293-#fJ3","version":10}'

组合查询

bool嵌套查询

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "city": "北京"
              }
            },
            {
              "term": {
                "channel": "百度"
              }
            }
          ]
        }
      }
    }
  }
}
 

查询多个准确值

{
  "query": {
    "filtered": {
      "filter": {
        "terms": {
          "city": [
            "苏州",
            "北京"
          ]
        }
      }
    }
  }
}
 

范围查询 

es的范围查询使用range过滤器

{
  "query": {
    "filtered": {
      "filter": {
        "range": {
          "version": {
            "gte": 1,
            "lte": 10
          }
        }
      }
    }
  }
}
{
  "query": {
    "filtered": {
      "filter": {
        "range": {
          "timestamp": {
            "gt": "2015-12-01 00:00:00",
            "lt": "2015-12-12 00:00:00"
          }
        }
      }
    }
  }
}

 注意:要想过滤出yyyy-MM-dd HH:mm:ss的日期格式的数据,需要在创建索引mappings的时候指定日期格式。比如:

{
  "mappings": {
    "products": {
      "properties": {
        "productID": {
          "type": "string",
          "index": "not_analyzed"
        },
        "name": {
          "type": "string",
          "index": "not_analyzed"
        },
        "timestamp": {
          "type": "date",
          "format": "yyyy-MM-dd HH:mm:ss"
        }
      }
    }
  }
}
{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "range": {
                "timestamp": {
                  "gt": "2015-12-01 00:00:00"
                }
              }
            },
            {
              "range": {
                "version": {
                  "gt": 1,
                  "lte": 10
                }
              }
            }
          ]
        }
      }
    }
  }
}

猜你喜欢

转载自oitebody.iteye.com/blog/2262914