繁体   English   中英

努力通过ElasticSearch返回的JSON进行映射

[英]Struggling to map through JSON returned from ElasticSearch

我在react.js + node.js + ElasticSearch项目中取得了进展。 但是,我遇到了一个似乎无法解决的问题。 我想从弹性返回json的特定内容(例如名称和描述),但是我只能返回整个命中结果。 我已经尝试过“ .forEach()”,“。map()”和“ .json()”,但是还没有弄清楚。 我希望能够显示每个结果命中的名称和描述。 任何输入都会很棒!

阵营:

 import React, { Component } from 'react'; import axios from 'axios'; import ResultClub from './components/ResultClub'; class App extends Component { constructor(props) { super(props); this.state = { result: [], userInput: '', searched: false, } } //assigning userInput a new value handleChange = event=> { event.preventDefault(); this.setState({userInput: event.target.value}); } //retreiving elastic search data using userinput handleSubmit = event=> { event.preventDefault(); axios.get('http://localhost:4000/search?query=' + this.state.userInput) .then(res => { var result = res.data; this.setState({ result: result, searched: true, }); console.log(this.state.result); console.log(this.state.userInput); }) } //if user has searched, display the data displayResults(props){ var searched = this.state.searched; if (searched){ return <p> { JSON.stringify(this.state.result) } </p>; } } render() { return ( <div className="App"> <h2>hello from react</h2> <form action="/search"> <input type="text" value={this.state.userInput} onChange={this.handleChange} placeholder="Search..." name="query" id="userText"/> <button type="submit" onClick={this.handleSubmit}><i>Search</i></button> </form> {(this.displayResults())} </div> ); } } export default App; 

节点:

 const express = require('express'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const JSON = require('circular-json'); const PORT = 4000; var client = require ('./connection.js'); var argv = require('yargs').argv; var getJSON = require('get-json'); const cors = require('cors'); let app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors({ origin: 'http://localhost:3001', credentials: true })); app.get('/', function(req, res){ res.send("Node is running brother"); }); app.get("/search", function (request, response) { let query = request.query.query; client.search({ index: 'club', type: 'clubinfo', body: { query: { match: { "name": query} }, } },function (error, data, status) { if (error) { return console.log(error); } else { // Send back the response response.send(data.hits.hits); } }); }); app.listen(PORT, () => console.log('wowzers in me trousers, Listening on port ' + PORT)); 

ElasticSearch返回(我想访问hits.hits中每个未修饰对象的_source.name):

 { took: 14, timed_out: false, -_shards: { total: 5, successful: 5, skipped: 0, failed: 0 }, -hits: { total: 1, max_score: 0.6931472, -hits: [ -{ _index: "club", _type: "clubinfo", _id: "Tl2B3mgB0CGswaMHFVwp", _score: 0.6931472, _source: { name: "Italian club", tags: "pasta, food, eating, italian", description: "we are italian!" } } -{ _index: "club", _type: "clubinfo", _id: "Tl2B3mgB0CGswaMHFVwp", _score: 0.3179638, _source: { name: "Old club", tags: "golf, chair", description: "we are Old people!" } } ] } } 

使用Array#map和解构从对象中获取所有名称。

 const data = {took:14,timed_out:false,_shards:{total:5,successful:5,skipped:0,failed:0},hits:{total:1,max_score:.6931472,hits:[{_index:"club",_type:"clubinfo",_id:"Tl2B3mgB0CGswaMHFVwp",_score:.6931472,_source:{name:"Italian club",tags:"pasta, food, eating, italian",description:"we are italian!"}},{_index:"club",_type:"clubinfo",_id:"Tl2B3mgB0CGswaMHFVwp",_score:.3179638,_source:{name:"Old club",tags:"golf, chair",description:"we are Old people!"}}]}} const res = data.hits.hits .map(({_source:{name,description}})=>({name,description})); console.log(res); 

根据您问题中的JSON判断,您想在this.state.result.hits.hits上使用map

class App extends Component {
  // ...

  render() {
    const { searched, result } = this.state;

    return (
      <div className="App">
        <h2>hello from react</h2>
        <form action="/search">
          <input
            type="text"
            value={this.state.userInput}
            onChange={this.handleChange}
            placeholder="Search..."
            name="query"
            id="userText"
          />
          <button type="submit" onClick={this.handleSubmit}>
            <i>Search</i>
          </button>
        </form>
        {searched && (
          <div>
            {result.hits.hits.map((hit, index) => (
              <div key={index}>
                {hit._source.name}: {hit._source.description}
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM