如何在即时搜索中停止复制? jquery + AJAX + mongoosastic

目前我正在使用的即时搜索工作正常,但只有一个问题。

每当我输入“化学”时,它都会显示查询

Chemical Engineer Chemical Entrepreneur Checmical People 

但是,假设我决定在“化学”之后添加“工程师”,结果将是

 Chemical Engineer Chemical Entrepreneur Checmical People Chemical Engineer Chemical Entrepreneur Checmical People 

这是代码

router.js

 router.post('/api/search/', function(req, res, next) { Product.search( { query_string: { query: req.body.search_term } } , function(err, results) { if (err) return next(err); res.json(results); }); }); 

custom.js

 $('#search').keyup(function() { // 1. grab the search term from the input field var search_term = $(this).val(); // 2. send it to your back-end via ajax in the body $.ajax({ method: "POST", url: "/api/search", // <-- your back-end endpoint data: { search_term }, // <-- what you're sending dataType: "json", // <-- what you're expecting back success: function(json){ // <-- do something with the JSON you get // 3. parse the JSON and display the results var res = json.hits.hits.map(function(hit) { return hit; }); console.log(res); for (var i = 0; i < res.length; i++) { $('.testing').append('
  • ' + res[i]._source.name + '
  • '); } }, error: function(data){ alert('Error', data); } }); });

    我该如何停止复制?

    使用curl -XGET localhost:9200 /产品/ _mapping由Val建议

     {"products":{"mappings":{"product":{"properties":{"_id":{"type":"string"},"category":{"type":"string"},"description":{"type":"string"},"image":{"type":"string"},"name":{"type":"string"},"price":{"type":"double"},"sizes":{"type":"string"},"stocks":{"type":"double"}}}}}} 

    我认为你应该清理普通的结果。 总是你按一个键你得到textfield的值,那个值将通过ajax发送。 如果您编写Chemical您将得到一些回复,这些回复将附加到您的html,所有那些回复与Chemical相匹配,所以当您编写Chemical Engineering您需要清理附带的附加标签,所以我认为这可能就足够了:

    custom.js

     $('#search').keyup(function() { // 1. grab the search term from the input field var search_term = $(this).val(); // 2. send it to your back-end via ajax in the body $.ajax({ method: "POST", url: "/api/search", // <-- your back-end endpoint data: { search_term }, // <-- what you're sending dataType: "json", // <-- what you're expecting back success: function(json){ // <-- do something with the JSON you get // 3. parse the JSON and display the results var res = json.hits.hits.map(function(hit) { return hit; }); console.log(res); $('.testing').empty(); ///new line added for (var i = 0; i < res.length; i++) { $('.testing').append('
  • ' + res[i]._source.name + '
  • '); } }, error: function(data){ alert('Error', data); } }); });

    PS:句子var search_term = $(this).val(); 没有必要的keyup函数为您提供通过参数eventelement

    https://api.jquery.com/keyup/