-1

我正在尝试从弹性搜索查询返回结果。这是我的网页

<!DOCTYPE html>
 <html>

  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  </head>

 <script>
 $(document).ready(function() {
 $('#ping-button').click(function(e) {
    e.preventDefault();

    var val;
    $.ajax({
        type: 'POST',
        url: 'http://localhost:6002/esPingTest',
        success: function(data){
        alert(data);
        alert("Yay");
        val=data;
        document.getElementById("demo").innerHTML = val;
        },
        error: function(){
        alert("Nay");
        }
    });


});
});
 </script>
<body>


<center>
<button id='ping-button'>Ping</button>
<br><br>
<p id="demo"></p>
</center>
</body>
</html>

所以我有一个按钮,当我点击它时,它应该去esPingTest方法。

这是我的 app.js

var express = require('express');
var app = express();
var cfenv = require('cfenv');
var bodyParser = require('body-parser');
var port = (process.env.VCAP_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');

// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('elastic'));

var appEnv = cfenv.getAppEnv();

//start server on the specified port and binding host
var server = app.listen(appEnv.port, '0.0.0.0', function() {

      console.log("server starting on " + appEnv.url);
    })

app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})


app.post('/esPingTest', urlencodedParser, function (req, res) {

   console.log("Ping");
   docs = getEsDocs()
   console.log(docs)
   res.end(JSON.stringify(docs));
})

function getEsDocs()
{
    var elasticsearch = require('elasticsearch');
    var client = elasticsearch.Client({
      host: 'localhost:9200',
      log: 'trace'
    });

    client.ping({
      // ping usually has a 3000ms timeout
      requestTimeout: Infinity,

      // undocumented params are appended to the query string
      hello: "elasticsearch!"
    }, function (error) {
      if (error) {
        console.trace('Elasticsearch cluster is down!');
        return "Error:Elasticsearch cluster is down!"
      } else {
        console.log('All is well');
        ff = getmeres(client);
        console.log("ping")
        console.log(ff)
        return ff
        //alert("YAY");
      }
    });

    function getmeres(client)
    {

        var xox =
        client.search({
              index: 'researchtest',
              body: {

                      "aggs": {
                        "docs": {
                          "terms": {
                            "field": "DocumentID"
                          }
                        }
                      }

              }
            }, function (error, response) {
                if (error) {
                    console.trace('Search query failed');
                    return "Error:Search query failed"
                  } else {
                    console.log('All is well');
                    d=response;
                    console.log("getmeres");
                    x=showdocs(d);
                    console.log("inner xo is"+xo);
                    var xo=x;
                    console.log("inner xo is"+xo);

                  }
            });
        console.log("outer xox is"+xox);
        return xox;
    }


    function showdocs(d){
        da=d.hits.hits
        var docs=[]
        for (i=0;i<da.length;i++)
        {   
            docs.push(da[i]["_source"]["DocumentID"]);
        }
        console.log("showdocs")
        console.log(docs)
        return docs;
    }

}

所以我showdocs()从函数的 else 条件中client.search调用函数

最后,我没有看到由于以下原因而返回的任何值return xo

这是我得到的结果

getmeres
showdocs
[ '12',
  '12',
  '23' ]
inner xo is[object Object]
inner xo 12,12,23

分配后如何取回 xo 的值xo=x

为什么最后一个console.log("outer xox is"+xox);根本没有打印出来?

我不知道如何将结果返回到我的网页

编辑

感谢@peteb 的回答。现在这是我的电话

var ff =  getmeres(client, function getmeresResult(err, result){
              if (err) return err;
              console.log("Got res "+result);
              return result;          
            });
        console.log("ping")
        console.log(ff)
        return ff;

getmeres正如你所建议的那样。现在我明白了

showdocs [ '12', '12', '23' ] 得到 res 12,12,23

这太棒了!但它仍然没有将值分配回ff. 我需要ff返回getEsDocs

getEsDocs我应该以同样的方式打电话getmeres吗?有回调?如果是这样,以下调用是否有效

docs = getEsDocs(function getDocResult(err, result){
      if (err) return err;
      console.log("Got doc "+result);
      return result;          
    })
   console.log(docs)
   res.end(JSON.stringify(docs));

差不多好了

再次感谢,我想我快到了

这是我的第一个电话

getEsDocs(function getDocResult(err, result){
      if (err) return err;
      console.log("Got doc "+result);
      res.end(JSON.stringify(result));
      return result;          
    })

这是我的第二个电话

function getEsDocs(callback)
{
    var elasticsearch = require('elasticsearch');
    var client = elasticsearch.Client({
      host: 'localhost:9200',
      log: 'trace'
    });

    client.ping({
      // ping usually has a 3000ms timeout
      requestTimeout: Infinity,

      // undocumented params are appended to the query string
      hello: "elasticsearch!"
    }, function (error) {
      if (error) {
        console.trace('Elasticsearch cluster is down!');
        return "Error:Elasticsearch cluster is down!"
      } else {
        console.log('All is well');
        return callback(null, getmeres(client, function getmeresResult(err, result){
              if (err) return err;
              console.log("Got res "+result);
              return result;          
            }));
      }
    });

它仍然打印

showdocs
    [ '12',
      '12',
      '23' ]
    Got res 12,12,23

我错过了什么?

几乎

所以这就是我所拥有的,正如你所建议的

app.post('/esPingTest', urlencodedParser, function (req, res) {

   console.log("Ping");
   getEsDocs(function getEsDocsResult(err, result) {
        if (err) return res.status(400).json(result);
        console.log("Got doc"+result)
        return res.status(200).json(result); 
      });

});

function getEsDocs(callback)
{
    var elasticsearch = require('elasticsearch');
    var client = elasticsearch.Client({
      host: 'localhost:9200',
      log: 'trace'
    });

    client.ping({
      // ping usually has a 3000ms timeout
      requestTimeout: Infinity,

      // undocumented params are appended to the query string
      hello: "elasticsearch!"
    }, function (error) {
      if (error) {
        console.trace('Elasticsearch cluster is down!');
        return "Error:Elasticsearch cluster is down!"
      } else {
        console.log('All is well');
        return callback(null, getmeres(client, getmeresResult));
        function getmeresResult(err, result)
        {
              if (err) return err;
              console.log("Got res "+result);
              return result;          
            }
      }
    });


}

但我仍然没有看到最终的回报!你能看出有什么不对吗?

所以基本上这个回报

if (err) return err;
              console.log("Got res "+result);
              return result;  

不工作!

4

2 回答 2

1

您的 finalconsole.log("outer xox is"+xox);不会被触发,因为它在调用后立即执行,client.search()因为该调用是异步的,并且不会阻止在该函数中继续执行。xoxundefined在这种情况发生时,因为console.log()如果它试图打印的内容与undefined.

您当前的实现getmeres()将始终返回undefined,因为您是从回调外部返回,而不是处理结果,client.search()然后从回调内部将该值返回给调用者。

您可以getmeres()通过将回调函数作为参数并返回带有结果的回调来获取值。请参阅下面的示例,其中第一个错误回调被作为getmeres().

function getmeres(client, callback) {
  client.search({
    index: 'researchtest',
    body: {
      "aggs": {
        "docs": {
          "terms": {
            "field": "DocumentID"
          }
        }
      }
    }
  }, function (error, response) {
    if (error) return callback(error, null); // returns the callback with the error that happened

    return callback(null, showdocs(response));  // returns the result of showdocs(response)
});

getmeres()使用回调作为第二个参数调用的示例

getmeres(client, function getmeresResult(err, result) {
  if (err) return err;

  return result;          
});

var elasticsearch = require('elasticsearch');,require()语句是同步的,您不应该将其放在 getEsDocs 中,因为每次命中此路由时,您将阻止运行快速服务器的主线程处理的所有操作

将值返回给路由:

app.post('/esPingTest', urlencodedParser, function (req, res) {
  getEsDocs(function getEsDocsResult(err, result) {
    if (error) return res.status(400).json(result);

    return res.status(200).json(result); 
  });
});

function getEsDocs(callback) {
  var client = elasticsearch.Client({
    host: 'localhost:9200',
    log: 'trace'
  });

  client.ping({
    // ping usually has a 3000ms timeout
    requestTimeout: Infinity,
    // undocumented params are appended to the query string
    hello: "elasticsearch!"
  }, function (error) {
      if (err) return callback(error, null);

      return callback(null, getmeres(client, getmeresResult));

      function getmeresResult(err, result) {
        if (err) return err;

        return result;          
      });
});
于 2016-02-11T22:07:29.440 回答
0

问题很可能是您xo多次使用。失败的行是尝试重新分配 to 的值,xox您仍在一个应该返回值 to 的函数调用中xo。如果你一开始就去掉var xo =,或者把它改成不同的变量名,你应该会看到它运行正常。

于 2016-02-11T22:09:10.067 回答