由于我们把ghost导入elasticsearch的时候,生成的id号是随机数。

结果导致搜索结果的顺序是随机的,很不好看。

我们先看一看mapping结构:

curl -XGET http://yi.zapto.org:12530/posts/_mapping?pretty=on  
{
  "posts" : {
    "mappings" : {
      "post" : {
        "_all" : {
          "analyzer" : "ik_max_word"
        },
        "properties" : {
          "content" : {
            "type" : "string",
            "boost" : 8.0,
            "term_vector" : "with_positions_offsets",
            "analyzer" : "ik_max_word",
            "include_in_all" : true
          },
          "slug" : {
            "type" : "string"
          },
          "tags" : {
            "type" : "string"
          },
          "title" : {
            "type" : "string"
          },
          "updated_at" : {
            "type" : "date",
            "format" : "strict_date_optional_time||epoch_millis"
          }
        }
      }
    }
  }
}

我们看到posts有content、slug、tags、title、updatedat几个属性。其中content是ik分词的,updatedat是日期,我们就按日期倒叙排列搜索结果好了。

看看之前的程序中发出elasticsearch的部分:

  var request_data = {
    "fields": ["content", "slug", "title", "tags", "updated_at"],
    "query": {
      "wildcard": {
        "_all": {
          "wildcard":   req.query.q + "*"
        }
      }
    },
    "highlight": {
      "fields": {
        "title": {},
        "tags": {},
        "content": {}
      }
    },
    "suggest": {
      "suggestions": {
        "text":  req.query.q,
        "term": {
          "field": "_all",
          "suggest_mode": "always"
        }
      }
    }
  };

增加一个sort

  var request_data = {
    "fields": ["content", "slug", "title", "tags", "updated_at"],
    "query": {
      "wildcard": {
        "_all": {
          "wildcard":   req.query.q + "*"
        }
      }
    },
    "highlight": {
      "fields": {
        "title": {},
        "tags": {},
        "content": {}
      }
    },
    "suggest": {
      "suggestions": {
        "text":  req.query.q,
        "term": {
          "field": "_all",
          "suggest_mode": "always"
        }
      }
    },
    "sort": {
       "updated_at": {
          "order": "desc"
        }
    }
  };

ok,这就可以了,搜出来的结果就按时间倒序排列了。

comments powered by Disqus