This article mainly introduces the use of powerful Elastisearch in Java Search engine example code, which has certain reference value. Those who are interested can learn about it
Elastisearch is a very powerful and easy-to-use engine. SearchIndexEngine
To run Elastisearch on the system, you only need the following steps
1. Download Elastisearch
The code is as follows:
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.4.0.zip
2. Unzip
unzip elasticsearch-5.4.0.zip
3. Run
elasticsearch-5.4.0/bin/elasticsearch
At this time, it may be killed directly. Because of memory overflow (OOM), elastisearch takes up a very large amount of memory. Therefore, when running on a server with relatively small memory, you must first modify the memory size of the jvm
vi elasticsearch-5.4.0/config/jvm.options
Change the stack size of lines 22 and 23 to 512M
-Xms512M -Xmx512M
If it is still killed after restarting, try again Change it to a smaller size
4. Whether the test is successful
curl 'http://localhost:9200/?pretty'
You can see the following return information:
{ "status": 200, "name": "Shrunken Bones", "version": { "number": "1.4.0", "lucene_version": "4.10" }, "tagline": "You Know, for Search" }
It means the startup is successful
Connect Next, we use Java's API to operate Elasticsearch
First, import the elastisearch and log4j packages
POM
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jk</groupId> <artifactId>ElasticsearchExample</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <!--用哪个版本就填什么--> <version>5.4.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.7</version> </dependency> </dependencies> </project>
The following are commonly used Several operations
1. Create client
Client client = null; try { client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); } catch (Exception e) { e.printStackTrace(); }
2. Create index
/** * 创建索引,有则先删除 * @param client */ private static void recreateIndex(Client client) { if (client.admin().indices().prepareExists(index).execute().actionGet() .isExists()) { DeleteIndexResponse deleteIndexResponse = client.admin().indices() .delete(new DeleteIndexRequest(index)).actionGet(); System.out.println("delete index :"); System.out.println(deleteIndexResponse); } CreateIndexResponse createIndexResponse = client.admin().indices() .prepareCreate(index).execute().actionGet(); System.out.println("create index :"); System.out.println(createIndexResponse); }
/** * 插入数据 * @param client */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void doIndex(final Client client) { Map s11 = new LinkedHashMap(); s11.put("title", "Think in java"); s11.put("origin", "美国"); s11.put("description", "初级java开发人员必读的书"); s11.put("author", "Bruce Eckel"); s11.put("price", 108); Map s12 = new LinkedHashMap(); s12.put("title", "Head First Java"); s12.put("origin", "英国"); s12.put("description", "java入门教材"); s12.put("author", "Kathy Sierra"); s12.put("price", 54); Map s21 = new LinkedHashMap(); s21.put("title", "Design Pattern"); s21.put("origin", "法国"); s21.put("description", "程序员不得不读的设计模式"); s21.put("author", "Kathy Sierra"); s21.put("price", 89); Map s22 = new LinkedHashMap(); s22.put("title", "黑客与画家"); s22.put("origin", "法国"); s22.put("description", "读完之后脑洞大开"); s22.put("author", "Paul Graham"); s22.put("price", 35); BulkResponse bulkResponse = client .prepareBulk() .add(client.prepareIndex(index, type).setId("11").setSource(s11).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("12").setSource(s12).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("21").setSource(s21).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("22").setSource(s22).setOpType(IndexRequest.OpType.INDEX).request()) .execute().actionGet(); if (bulkResponse.hasFailures()) { System.err.println("index docs ERROR:" + bulkResponse.buildFailureMessage()); } else { System.out.println("index docs SUCCESS:"); System.out.println(bulkResponse); } }
4.QueryAll
/** * 查询所有 */ private static void searchAll(Client client) { SearchResponse response = client.prepareSearch(index) .setQuery(QueryBuilders.matchAllQuery()) .setExplain(true).execute().actionGet(); System.out.println("searchAll : "); for (SearchHit searchHit : response.getHits()) { System.out.println("********"); System.out.println(searchHit.getSource()); } }
5.Keyword query
/** * 关键词查询 * * @param client */ private static void searchKeyWord(Client client) { SearchResponse response = client.prepareSearch(index) //查询所有字段匹配关键字 .setQuery(QueryBuilders.matchQuery("_all", "法国")) //设置最小匹配程度 // .setQuery(QueryBuilders.matchQuery("_all", "法国").minimumShouldMatch("100%")) .execute().actionGet(); System.out.println("searchKeyWord : "); System.out.println(response); }
6. Numeric range filtering
/** * 数值范围过滤 * * @param client */ private static void searchRange(Client client) { SearchResponse response = client.prepareSearch(index). //大于80,小于100 setQuery(QueryBuilders.rangeQuery("price").gt(80).lt(100)) .execute() .actionGet(); System.out.println("searchRange : "); System.out.println(response); }
7. Sorting
/** * 排序 * * @param client */ private static void searchOrdered(Client client) { SearchResponse response = client.prepareSearch(index) .setQuery(QueryBuilders.matchAllQuery()) //根据价格降序排序 .addSort(SortBuilders.fieldSort("price") .order(SortOrder.DESC)).execute().actionGet(); System.out.println("searchOrdered : "); System.out.println(response); }
8.Highlight keywords
/** * 高亮关键字 * @param client */ private static void searchHightlight(Client client) { //高亮多个字段 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("title"); highlightBuilder.field("description"); SearchResponse response = client.prepareSearch(index) //单条件匹配,高亮时只能高亮该字段 // .setQuery(QueryBuilders.matchQuery("title", "java")) //多条件匹配,高亮时只能高亮多个字段 .setQuery(QueryBuilders.multiMatchQuery("开发人员必读", "title", "description")) .highlighter(highlightBuilder) .execute() .actionGet(); System.out.println("searchHightlight : "); System.out.println(response); }
9. Search
/** * 根据id查找 * @param client */ private static void findById(final Client client) { String id="12"; GetResponse response = client.prepareGet(index, type, id).get(); System.out.println("findById"); System.out.println(response); }
10. Delete
/** * 删除 * @param client */ private static void deleteById(Client client) { String id="12"; DeleteResponse response = client.prepareDelete(index, type, id).get(); }
11.Update
/** * 更新 * @param client */ private static void updateById(Client client) { try { String id="11"; client.prepareUpdate(index, type, id) .setDoc(jsonBuilder() .startObject() .field("title", "白鹿原") .endObject()) .get(); } catch (IOException e) { e.printStackTrace(); } }
The above is the detailed content of Example code for using the powerful Elastisearch search engine in Java. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor