GVKun编程网logo

在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑?

25

想了解在C#中使用NEST库调用elasticsearch时如何向linq语句添加条件逻辑?的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于ElasticSearch(一)Elasti

想了解在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑?的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于ElasticSearch (一) ElasticSearch 的应用场景及为什么要选择 ElasticSearch?、ElasticSearch - ElasticSearch和kinaba的简单使用、Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项、ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch的新知识。

本文目录一览:

在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑?

在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑?

如何解决在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑??

我正在尝试在 C# 中使用流畅的 LINQ 来使用 .NET NEST library 查询 Elasticsearch 服务器。

我想根据传入的搜索请求构建 LINQ 语句。如果搜索请求有价格范围,我想在 Elasticsearch 请求中添加一个范围子句。这是我的代码

var products = await client.SearchAsync<Product>(x =>
{
      x = x.Query(q =>
      {
          if (request.IsAvailable.HasValue)
          {
               // this gets called,but it is never added to the final elasticsearch call.
              q = q.Match(b => b.Field(bm => bm.IsAvailable).Query(request.IsAvailable.Value ? "true" : "false")) as QueryContainerDescriptor<Product>;
          }

          if (request.MinPrice.HasValue || request.MaxPrice.HasValue)
          {
              // this gets called,but it is never added to the final elasticsearch call.
              q = q.Range(r =>
              {
                  if (request.MinPrice.HasValue)
                  {
                      r = r.Field(x => x.Price).GreaterThanorEquals(request.MinPrice.Value);
                  }

                  if (request.MaxPrice.HasValue)
                  {
                      r = r.Field(x => x.Price).LessthanorEquals(request.MaxPrice.Value);
                  }
                  return r;
              }) as QueryContainerDescriptor<Product>;
          }

          if (request.Types != null && request.Types.Length > 0)
          {
              // this gets called,but it is never added to the final elasticsearch call.
              q = q.Terms(t => t.Field(f => f.Type).Terms(request.Types)) as QueryContainerDescriptor<Product>;
          }

          return q;
      });

      x = x.source(s => s.Excludes(se =>
      {
          // This works! There fields are being excluded as expected
          if (request.ExcludeSummary)
          {
              se = se.Field(sef => sef.Summary);
          }

          if (request.ExcludeTimestamp)
          {
              se = se.Field(sef => sef.Timestamp);
          }

          if (request.ExcludeLabels)
          {
              se = se.Field(sef => sef.Labels);
          }

          if (request.ExcludeTags)
          {
              se = se.Field(sef => sef.Tags);
          }

          return se;
      }));

      return x;
});

我在 Query() 中的所有条件都没有添加到 elasticsearch 请求中。这意味着生成的 json 请求没有价格或 IsAvaliable 子句。我怀疑演员是罪魁祸首,但不知道如何解决。

Source() 按预期工作。它将正确的字段添加到 excludes 列表中。

如何将查询子句正确添加到 Query() 部分?

解决方法

我发现了这个问题。似乎 NEST 取了最后一个子句,而忽略了前面的所有子句。

这是我为修复它所做的

var products = await client.SearchAsync<Product>(x =>
{
      x = x.Query(q =>
      {
          QueryContainer qc = q;

          if (request.IsAvailable.HasValue)
          {
              qc = qc && +q.Match(b => b.Field(bm => bm.IsAvailable).Query(request.IsAvailable.Value ? "true" : "false"));
          }

          if (request.MinPrice.HasValue || request.MaxPrice.HasValue)
          {
              qc = qc && +q.Range(r =>
              {
                  if (request.MinPrice.HasValue)
                  {
                      r = r.Field(x => x.Price).GreaterThanOrEquals(request.MinPrice.Value);
                  }

                  if (request.MaxPrice.HasValue)
                  {
                      r = r.Field(x => x.Price).LessThanOrEquals(request.MaxPrice.Value);
                  }
                  return r;
              });
          }

          if (request.Types != null && request.Types.Length > 0)
          {
              qc = qc && +q.Terms(t => t.Field(f => f.Type).Terms(request.Types));
          }

          return qc;
      });

      x = x.Source(s => s.Excludes(se =>
      {
          if (request.ExcludeSummary)
          {
              se = se.Field(sef => sef.Summary);
          }

          if (request.ExcludeTimestamp)
          {
              se = se.Field(sef => sef.Timestamp);
          }

          if (request.ExcludeLabels)
          {
              se = se.Field(sef => sef.Labels);
          }

          if (request.ExcludeTags)
          {
              se = se.Field(sef => sef.Tags);
          }

          return se;
      }));

      return x;
});

ElasticSearch (一) ElasticSearch 的应用场景及为什么要选择 ElasticSearch?

ElasticSearch (一) ElasticSearch 的应用场景及为什么要选择 ElasticSearch?

先了解一下数据的分类

结构化数据
又可以称之为行数据,存储在数据库里,可以用二维表结构来逻辑表达实现的数据。其实就是可以能够用数据或者统一的结构加以表示的数据。比如在数据表存储商品的库存,可以用整型表示,存储价格可以用浮点型表示,再比如给用户存储性别,可以用枚举表示,这都是结构化数据。

非结构化数据
无法用数字或者统一的结构表示的数据,称之为飞结构化数据。如:文本、图像、声音、网页。
其实结构化数据又数据非结构化数据。商品标题、描述、文章描述都是文本,其实文本就是非结构化数据。那么就可以说非结构化数据即为全文数据。

什么是全文检索?

一种将文件或者数据库中所有文本与检索项相匹配的文字资料检索方法,称之为全文检索。

全文检索的两种方法

顺序扫描法:将数据表的所有数据逐个扫描,再对文字描述扫描,符合条件的筛选出来,非常慢!
索引扫描法:全文检索的基本思路,也就是将非结构化数据中的一部分信息提取出来,重新组织,使其变得有一定结构,然后对此有一定结构的数据进行搜索,从而达到搜索相对快的目的。

全文检索的过程:
先索引的创建,然后索引搜索

为什么要选择用 ElasticSearch?

全文搜索属于最常见的需求,开源的 Elasticsearch (以下简称 Elastic)是目前全文搜索引擎的首选。
Elastic 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接口,开箱即用。
分布式的实时文件存储,每个字段都被索引可被搜索。
分布式的实时分析搜索引擎。
可以扩展到上百台服务器,处理 PB 级别结构化或者非结构化数据。
所有功能集成在一个服务器里,可以通过 RESTful API、各种语言的客户端甚至命令与之交互。
上手容易,提供了很多合理的缺省值,开箱即用,学习成本低。
可以免费下载、使用和修改。
配置灵活,比 Sphinx 灵活的多。

ElasticSearch - ElasticSearch和kinaba的简单使用

ElasticSearch - ElasticSearch和kinaba的简单使用

ElasticSearch和kinaba的简单使用

ElasticSeatch 文档推荐 

ElasticSearch 下载 (端口 9200)

安装好es,可以访问 http://localhost:9200/ 

 

Kibana (es的可视化界面,ELB框架),kibana (5601)

 

elasticsearch基本概念:

  • cluster 整个es默认就是集群状态,整个集群是一份互备的数据
  • node : 一个节点一台机器
  • shard:  分片,即时是一个节点中的数据也会通过hash算法,分成多个片存放,默认是5片
  • index:相当于database,对于用户来说就是一个逻辑数据库,虽然物理上是分成多个shard存放的
  • type: 相当于与table,但是与其想是table但是其实更像面向对象中的class,同一个json的格式的数据集合。 
  • document: 相当于表中的行,面向对象的object
  • field: 相当于字段、属性

 DSL语言:

插入: PUT 数据

PUT /megacorp/employee/1
{
    "first_name" : "John",
    "last_name" :  "Smith",
    "age" :        25,
    "about" :      "I love to go rock climbing",
    "interests": [ "sports", "music" ]
}
megacorp是索引 index 
employee是type
上面
PUT /megacorp/employee/1的含义是 在索引为megacorp并且type为employee中插入id为1

GET /_cat/indices?v

 查询 GET

修改PUT 覆盖

POST movie_index/movie/3/_update 修改内容但不覆盖

删除  逻辑上删除

Delete movie_index/movie/3

查询全部 GET movie_index/movie/_search

 

match_phrase : 多匹配

 

es的配置:

 

Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项

Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项

如何解决Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项?

我是 elasticSearch 的新手,我正在尝试查询与地图上特定点匹配的文档,我正在使用 GeoPoint 对象,我需要进行一个返回所有“地理区域”的查询包含此句点,但我对 elasticsearch 查询有些困惑。

我仍然没有正确理解为了执行这些操作我的文档必须具有的结构,在这里我离开我正在调用的文档的类

@Data
@Document(indexName = "geozona")
public class GeozonaElasticDTO {

    @Id
    @Field(type = FieldType.Long)
    private long id;

    @Field(type = FieldType.Text)
    private UUID uuid;

    @Field(type = FieldType.Text)
    private String nombre;

    @Field(type = FieldType.Text)
    private String descripcion;

    private List<UUID> etiquetas;

    private List<UUID> lugares;

    private List<UUID> geozonaLimiteVeLocidad;

    @Field(type = FieldType.Text)
    private EnumTipoGeozona tipoGeozona;

    @Field(type = FieldType.Double)
    private Double radio;

    @Field(type = FieldType.Text)
    private String pathEncode;

    @Field(type = FieldType.Object)
    @GeoPointField
    private List<GeoPoint> points;

    @Field(type = FieldType.Double)
    private double puntoDeReferenciaLatitud;

    @Field(type = FieldType.Double)
    private double puntoDeReferenciaLongitud;

    @Field(type = FieldType.Integer)
    private int limiteDeOrientacionGradoInicio;

    @Field(type = FieldType.Integer)
    private int limiteDeOrientacionGradoTermino;

    @Field(type = FieldType.Integer)
    private Integer ancho;

    @Field(type = FieldType.Boolean)
    private boolean eliminado;

    @Field(type = FieldType.Date,format = DateFormat.custom,pattern = "uuuu-MM-dd''T''HH:mm:ssZ")
    private zoneddatetime fechaCreacion;

    @Field(type = FieldType.Date,pattern = "uuuu-MM-dd''T''HH:mm:ssZ")
    private zoneddatetime fechaActualizacion;

    @Field(type = FieldType.Integer)
    private int version;
}

这是我在弹性服务器中的类的结构

    "geozona": {
        "aliases": {},"mappings": {
            "properties": {
                "_class": {
                    "type": "text","fields": {
                        "keyword": {
                            "type": "keyword","ignore_above": 256
                        }
                    }
                },"ancho": {
                    "type": "integer"
                },"descripcion": {
                    "type": "text"
                },"eliminado": {
                    "type": "boolean"
                },"etiquetas": {
                    "type": "text","fechaActualizacion": {
                    "type": "date","format": "uuuu-MM-dd''T''HH:mm:ssZ"
                },"fechaCreacion": {
                    "type": "date","geozonaLimiteVeLocidad": {
                    "type": "text","id": {
                    "type": "keyword"
                },"limiteDeOrientacionGradoInicio": {
                    "type": "integer"
                },"limiteDeOrientacionGradoTermino": {
                    "type": "integer"
                },"lugares": {
                    "type": "text","nombre": {
                    "type": "text"
                },"pathEncode": {
                    "type": "text"
                },"points": {
                    "type": "geo_point"
                },"puntoDeReferenciaLatitud": {
                    "type": "double"
                },"puntoDeReferenciaLongitud": {
                    "type": "double"
                },"radio": {
                    "type": "double"
                },"tipoGeozona": {
                    "type": "text"
                },"uuid": {
                    "type": "text"
                },"version": {
                    "type": "integer"
                }
            }
        },"settings": {
            "index": {
                "refresh_interval": "1s","number_of_shards": "1","provided_name": "geozona","creation_date": "1609949683125","store": {
                    "type": "fs"
                },"number_of_replicas": "1","uuid": "m-y7Qa5wSwGmDA3TVm4HkA","version": {
                    "created": "7090299"
                }
            }
        }
    }
}

如果有人能指导我如何开始正确处理地理定位点与弹性的重合,那将对我有很大帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch

ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch

 

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.16.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.huarui</groupId>
    <artifactId>sb_elasticsearch_jestclient</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sb_elasticsearch_jestclient</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.7</version>
        </dependency>
        <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>
    </dependencies>

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

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>
pom.xml

 

		<dependency>
			<groupId>io.searchbox</groupId>
			<artifactId>jest</artifactId>
			<version>5.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<version>5.6.7</version>
		</dependency>

 

spring.elasticsearch.jest.uris = http://192.168.79.129:9200/
spring.elasticsearch.jest.read-timeout = 10000
spring.elasticsearch.jest.username =
spring.elasticsearch.jest.password =

 

junit

 

import com.huarui.entity.User;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.mapping.GetMapping;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticApplicationTests {

    private static String indexName = "userindex";
    private static String typeName = "user";

    @Autowired
    JestClient jestClient;

    /**
     * 新增数据
     * @return
     * @throws Exception
     */
    @Test
    public void insert() throws Exception {
        User user = new User(1L, "张三", 20, "张三是个Java开发工程师","2018-4-25 11:07:42");
        Index index = new Index.Builder(user).index(indexName).type(typeName).build();
        try{
            JestResult jr = jestClient.execute(index);
            System.out.println(jr.isSucceeded());
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}

 

 

我们今天的关于在 C# 中使用 NEST 库调用 elasticsearch 时如何向 linq 语句添加条件逻辑?的分享就到这里,谢谢您的阅读,如果想了解更多关于ElasticSearch (一) ElasticSearch 的应用场景及为什么要选择 ElasticSearch?、ElasticSearch - ElasticSearch和kinaba的简单使用、Elasticsearch - 如何在java中使用elasticsearch查找与地理定位点的匹配项、ElasticSearch - 学习笔记 02-springboot 整合 jestclient 操作 elasticSearch的相关信息,可以在本站进行搜索。

本文标签: