ElasticSearch教程——Java进行搜索

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gwd1154978352/article/details/82775853

更多Java相关操作请移步:ElasticSearch教程——Java常用操作

pom.xml

<?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.elasticsearch</groupId>
	<artifactId>elasticSearch</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>elasticSearch</name>
	<description>Demo project for elasticsearch</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<elsaticsearch.version>6.4.0</elsaticsearch.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
		    <groupId>org.elasticsearch.client</groupId>
		    <artifactId>elasticsearch-rest-client</artifactId>
		    <version>${elsaticsearch.version}</version>
		</dependency>
		<dependency>
	        <groupId>org.elasticsearch.client</groupId>
	        <artifactId>transport</artifactId>
	        <version>${elsaticsearch.version}</version>
		</dependency>
		<dependency>
	        <groupId>org.elasticsearch.plugin</groupId>
	        <artifactId>transport-netty4-client</artifactId>
	        <version>${elsaticsearch.version}</version>
	   </dependency>
		<dependency>
		    <groupId>org.elasticsearch</groupId>
		    <artifactId>elasticsearch</artifactId>
		    <version>${elsaticsearch.version}</version>
		</dependency>
		<dependency>
		    <groupId>org.elasticsearch.client</groupId>
		    <artifactId>elasticsearch-rest-high-level-client</artifactId>
		    <version>${elsaticsearch.version}</version>
		    <type>pom</type>
		</dependency>
		<dependency>
		    <groupId>commons-lang</groupId>
		    <artifactId>commons-lang</artifactId>
		    <version>2.6</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

HandleDocument.java

package com.gwd.elasticsearch.test;

import java.net.InetAddress;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Description:
 * 作者:gu.weidong(Jack)
 * date:2018年9月18日
 * ProjectName:elasticSearch
 */
public class HandleDocument{
	
	private  TransportClient client = null;
	
	
	@Test
	public  void getResult() throws Exception{
		SearchResponse response = client.prepareSearch("blog","index")//创建查询索引,参数productindex表示要查询的索引库为blog、index
		        .setTypes("article")  //设置type
		        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)//设置查询类型 1.SearchType.DFS_QUERY_THEN_FETCH = 精确查询  2.SearchType.SCAN =扫描查询,无序
		        .setQuery(QueryBuilders.termQuery("content", "today"))  //设置查询项以及对应的值
	//	        .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // 设置Filter过滤
		        .setFrom(0).setSize(60)//设置分页
		        .setExplain(true) //设置是否按查询匹配度排序
		//        .addSort("id", SortOrder.DESC)//设置按照id排序
		        .execute()
		        .actionGet();
		SearchHits hits = response.getHits();
		System.out.println("总数:"+hits.getTotalHits());
		for(SearchHit hit: hits.getHits()) {
		    if(hit.getSourceAsMap().containsKey("title")) {
		    	System.out.println("source.title: " + hit.getSourceAsMap().get("title"));
		    }
		}
		System.out.println(response.toString());
		closeClient();
	}
	
	
	
	// 获取客户端
	@Before
	public   void getClient() throws Exception{
		Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch").build();
		client =  new PreBuiltTransportClient(settings). addTransportAddress(new TransportAddress(InetAddress.getByName("XXX.XXX.XX.XX"), 9300));
	}
	
	// 关闭客户端
	@After
	public  void closeClient(){
		if (this.client != null){
			this.client.close();
		}
	}
	
}

返回结果

总数:2
source.title: New version of Elasticsearch released!
source.title: New version of Elasticsearch released!
{
	"took": 7,
	"timed_out": false,
	"_shards": {
		"total": 10,
		"successful": 10,
		"skipped": 0,
		"failed": 0
	},
	"_clusters": {
		"total": 0,
		"successful": 0,
		"skipped": 0
	},
	"hits": {
		"total": 2,
		"max_score": 0.61827284,
		"hits": [{
			"_shard": "[blog][1]",
			"_node": "xDV-GTebTRqc7es0hDR4rQ",
			"_index": "blog",
			"_type": "article",
			"_id": "eTmX5mUBtZGWutGW0TNs",
			"_score": 0.61827284,
			"_source": {
				"title": "New version of Elasticsearch released!",
				"content": "Version 1.0 released today!",
				"priority": 10,
				"tags": ["announce", "elasticsearch", "release"]
			},
			"_explanation": {
				"value": 0.61827284,
				"description": "weight(content:today in 0) [PerFieldSimilarity], result of:",
				"details": [{
					"value": 0.61827284,
					"description": "score(doc=0,freq=1.0 = termFreq=1.0\n), product of:",
					"details": [{
						"value": 0.47000363,
						"description": "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:",
						"details": [{
							"value": 2.0,
							"description": "docFreq",
							"details": []
						}, {
							"value": 3.0,
							"description": "docCount",
							"details": []
						}]
					}, {
						"value": 1.3154639,
						"description": "tfNorm, computed as (freq * (k1 + 1)) / (freq + k1 * (1 - b + b * fieldLength / avgFieldLength)) from:",
						"details": [{
							"value": 1.0,
							"description": "termFreq=1.0",
							"details": []
						}, {
							"value": 1.2,
							"description": "parameter k1",
							"details": []
						}, {
							"value": 0.75,
							"description": "parameter b",
							"details": []
						}, {
							"value": 9.666667,
							"description": "avgFieldLength",
							"details": []
						}, {
							"value": 4.0,
							"description": "fieldLength",
							"details": []
						}]
					}]
				}]
			}
		}, {
			"_shard": "[blog][3]",
			"_node": "xDV-GTebTRqc7es0hDR4rQ",
			"_index": "blog",
			"_type": "article",
			"_id": "1",
			"_score": 0.61827284,
			"_source": {
				"id": "1",
				"title": "New version of Elasticsearch released!",
				"content": "Version 1.0 released today!",
				"priority": 10,
				"tags": ["announce", "elasticsearch", "release"]
			},
			"_explanation": {
				"value": 0.61827284,
				"description": "weight(content:today in 0) [PerFieldSimilarity], result of:",
				"details": [{
					"value": 0.61827284,
					"description": "score(doc=0,freq=1.0 = termFreq=1.0\n), product of:",
					"details": [{
						"value": 0.47000363,
						"description": "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:",
						"details": [{
							"value": 2.0,
							"description": "docFreq",
							"details": []
						}, {
							"value": 3.0,
							"description": "docCount",
							"details": []
						}]
					}, {
						"value": 1.3154639,
						"description": "tfNorm, computed as (freq * (k1 + 1)) / (freq + k1 * (1 - b + b * fieldLength / avgFieldLength)) from:",
						"details": [{
							"value": 1.0,
							"description": "termFreq=1.0",
							"details": []
						}, {
							"value": 1.2,
							"description": "parameter k1",
							"details": []
						}, {
							"value": 0.75,
							"description": "parameter b",
							"details": []
						}, {
							"value": 9.666667,
							"description": "avgFieldLength",
							"details": []
						}, {
							"value": 4.0,
							"description": "fieldLength",
							"details": []
						}]
					}]
				}]
			}
		}]
	}
}

猜你喜欢

转载自blog.csdn.net/gwd1154978352/article/details/82775853