elasticsearch - 如何在 Elasticsearch 中添加文档?

标签 elasticsearch

嗨,我有Maven项目。我正在尝试 flex 搜索。所以我有一个Junit测试类,我试图在其中启动一个嵌入式 flex 搜索实例。我能够创建一个名为cars的索引,然后将car键入到cars索引中。我想做的是将100辆汽车加满到索引中。

所以下面是我的代码。

public class ElasticSearchTest {

    private static EmbeddedElastic embeddedElastic;

    @BeforeClass
    public static void init() throws IOException, InterruptedException {

        embeddedElastic = EmbeddedElastic.builder().withElasticVersion("6.1.1")
                .withSetting(PopularProperties.TRANSPORT_TCP_PORT, 9350)
                .withSetting(PopularProperties.CLUSTER_NAME, "my_cluster")
                .withStartTimeout(2, TimeUnit.MINUTES)
                  .withIndex("cars", IndexSettings.builder()
                            .withType("car", getSystemResourceAsStream())
                            .build())
                .build()
                .start();

    }

    private static InputStream getSystemResourceAsStream() throws FileNotFoundException {

        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("car-mapping.json");
        return is;
    }

    @Test
    public void test() {
        System.out.println("Hello world");
    }

    @AfterClass
    public static void close() {
        embeddedElastic.stop();
    }

}

car-mapping.json
{
  "car": {
    "properties": {
      "manufacturer": {
        "type": "text",
        "index": "false"
      },
      "model": {
        "type": "text",
        "index": "true"
      },
      "description": {
        "type": "text"
      }
    }
  }
}

我如何用junit测试中的一些数据填充索引

非常感谢任何帮助
谢谢

最佳答案

我做了一些可能对您有帮助的代码,我使用了一些文本编辑器,因此可能会有一些错误/未使用的导入,但是您可以了解如何做。

package your.package;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.swing.text.MaskFormatter;

import com.google.gson.JsonObject;
import com.opencsv.CSVReader;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;
import org.apache.http.HttpHost;


import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class App implements CommandLineRunner {

    @Override
    public void run(String... args)
            throws Exception, NullPointerException, IllegalStateException, IllegalArgumentException {

        String host = "localhost";

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, 9200, "http")).setMaxRetryTimeoutMillis(90000000));

        BulkRequest bulk = new BulkRequest();
        IndexRequest indexRequest = null;


        JsonObject jsonDoc = null;
        jsonDoc = new JsonObject();


     //JSON parser object to parse read file
     JSONParser jsonParser = new JSONParser();

     try (FileReader reader = new FileReader("car-mapping.json"))
     {
         //Read JSON file
         Object obj = jsonParser.parse(reader);

         JSONArray carMapping = (JSONArray) obj;

         //Iterate over employee array
         carMapping.forEach(emp -> parseCarMappingObject( (JSONObject) emp ) );

     } catch (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     } catch (ParseException e) {
         e.printStackTrace();
     }


     // Close your parser /  Elastic Client
        jsonParser.close();
        client.close();

  }

  private static void parseCarMappingObject(JSONObject employee)
    {
        //Get employee object within list
        JSONObject properties = (JSONObject) employee.get("properties");

        //Get employee first name
        String manufacturer = (String) employeeObject.get("manufacturer");  

        // Get your data, depending on how your json are.
        // Create one JSON object with the data you want to Index.

        // For example
        jsonDoc.addProperty("manufacturer", manufacturer);

        // Then, Index your Data.

        // I generally use _doc as doc type, you can change to whatever you want
        indexRequest = new IndexRequest("your_index_name", "_doc").source(jsonDoc.toString(),
        XContentType.JSON);


        // If your data is too big, use bulk to index it faster
        bulk.add(indexRequest);

        // Do your logic here to Index it depending on its size.
        if (index % 10000 == 0 && index > 0) {
          client.bulk(bulk, RequestOptions.DEFAULT);
          bulk.requests().clear();
        } else if (index > 740000) {
          client.index(indexRequest, RequestOptions.DEFAULT);
        }
    }

  }

}

关于elasticsearch - 如何在 Elasticsearch 中添加文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549017/

相关文章:

python - 如何使用 API key 和 python 库正确连接到 Elasticsearch 云?

python - 更新到 elasticsearch 2.3 后无法定位嵌套的地理点

elasticsearch - 添加requestTimeout会导致Kibana在启动时失败

sorting - Elasticsearch 按字母顺序排序,然后按数字排序

java - 使用 Java API 时如何在 ElasticSearch 中使用特定的分析器

elasticsearch - 通过Elasticsearch中的查询更新

arrays - 对象数组上的Elasticsearch脚本过滤器

amazon-web-services - AWS EC2 实例不会加载 Kibana

scala - 在 Scala 规范中同步之前/之后的方法?

apache - 语法错误,使用fq(过滤查询)时无法从lucene StandardQueryparser进行解析