当前位置:网站首页>Redis OM . Net redis object mapping framework
Redis OM . Net redis object mapping framework
2022-06-26 16:49:00 【Masa technical team】
Redis OM
Redis OM yes Redis The official object mapping framework , namely :Object Mapping. Make it easier for developers 、 Convenient operation Redis data .Redis The stored data is abstracted as object mapping , Support object-based Redis Data persistence 、 Streaming query operation .
Currently only supported 4 Development languages :
- Redis OM for Spring
- Redis OM for .NET
- Redis OM for Node.js
- Redis OM for Python
Redis OM .NET
Redis OM .NET yes .Net Platform Redis OM, rely on StackExchange.Redis Realization . With the help of Redis OM .NET Can realize the way of object operation Redis data , Out of the key/value How to operate . Query supports most .Neter favorite LINQ.
Quick start
Install the corresponding package
dotnet add package Redis.OMRedis Environmental preparation
Use it directly Docker Mode of installation Redis Environmental Science .
docker run -p 6379:6379 redislabs/redismod:previewThe standard official image cannot support Redis OM, need Redis Modules Support ,Redis OM Core index creation 、 Query data dependency
RediSearchThis Module Realization . Rely on the Module Yes :RediSearch、RedisJSON. RedisJSON Dependency is not necessary , But there will be a lack of corresponding functions , Such as : Model nesting 、 Complex queries ( Only support key Inquire about )
Coding
Add abstract object definition
[Document]public class Customer{ [RedisIdField] public string Id { get; set; } [Indexed(Sortable = true, Aggregatable = true)] public string FirstName { get; set; } [Indexed(Sortable = true, Aggregatable = true)] public string LastName { get; set; } [Indexed] public string Email { get; set; } [Indexed(Sortable = true)] public int Age { get; set; }}Document、Indexed、Searchable Introduction to other characteristics , Introduces the reference Github -> document-attribute
Get the operation collection of abstract objects 、 Create index
var provider = new RedisConnectionProvider("redis://localhost:6377");var connection = provider.Connection;var customers = provider.RedisCollection<Customer>();connection.CreateIndex(typeof(Customer)); Query data 、 Aggregation operations need to be based on the index , So be sure to call connection.CreateIndex Create index , Corresponding RediSearch Of FT.CREATE command .
connection.CreateIndex(typeof(Customer)) An exception is thrown when the index is created repeatedly
Index already exists. Although it can passconnection.Execute("FT.INFO", $"customer-idx")Get index information , But the first time the index does not exist, it will throwUnknown Index name. So in actual use, you may need a try-catch encaseCreateIndexMethods to avoid exceptions .
insert data
var id = customers.Insert(new Customer { FirstName = "Steve", Email = "[email protected]", Age = 1 });var id2 = customers.Insert(new Customer { FirstName = "FirstName", LastName = "LastName", Email = "[email protected]" });id,id2 For inserting data key, Is not specified Document Of Prefixes and IdGenerationStrategy, The default is ULID The format is {DocumentName}:{Ulid}, Such as :`Cust
When inserting data, you should pay attention to , If the value of the field is not explicitly specified , Such as LastName Ambiguous assignment :
customers.Insert(new Customer { FirstName = "Steve", Email = "[email protected]", Age = 1 });, see Redis The data stored in can find the current key Stored json The data does not correspond to an unspecified field key( here Query or Aggregations There will be some strange mistakes ). According to their own needs , The displayed field is assigned a zero value or used when defining an entitypublic string LastName { get; set; } = string.Empty;The way .
Query data
var customer = customers.Where(x => x.Age == 0).OrderBy(a => a.FirstName).FirstOrDefault();var customerById = customers.FindById(id);// according to Id lookup var emails = customers.Select(x => x.Email);// Query only the specified fields var takes = customers.Where(x => x.Age > 0).Take(10);// Get the specified number var adults = customers.Where(x => x.Age >= 0).Skip(5);// Query offset Judgment of null value ,x.FirstName == ""【 Grammar mistakes 】 or string.IsNullOrEmpty(x.FirstName)【 I won't support it 】.Redis Cannot have empty string in hash , Therefore, similar queries should be operated through aggregation Exists Method realization
foreach (var agg in customerAggregations.Apply(x => ApplyFunctions.Exists(x.RecordShell.LastName), "LastNameExists")){ Console.WriteLine($"{agg["LastNameExists"]}");}Aggregation operation
Assembly line (Pipelining) Send multiple requests at the same time , So as to reduce the delay . The query and transformation of the results are Redis The complete .
RecordShell It's the far end Index The structure of the type ,RecordShell Should only be used inside the aggregation pipeline , There is no real value at runtime .
Put together FirstName and LastName, return FullName
var customerAggregations = provider.AggregationSet<Customer>();var age = customerAggregations.Average(x => x.RecordShell.Age);var sets = customerAggregations.Where(a => a.RecordShell.FirstName == "Steve").Apply(x => string.Format("{0} {1}", x.RecordShell.FirstName, x.RecordShell.LastName), "FullName");foreach (var item in sets){ Console.WriteLine(item["FullName"].ToString());}Group together
adopt GroupBy Method , Group and aggregate according to different attributes ( Support single field grouping and multi field grouping ).
var res = customerAggregations .GroupBy(x => x.RecordShell.FirstName) .GroupBy(x => x.RecordShell.LastName) .ToArray();var res1 = customerAggregations.GroupBy(x => x.RecordShell.FirstName).CloseGroup().ToArray();CloseGroup You can turn off grouping , Convert to normal aggregation operation , namely GroupedAggregationSet To RedisAggregationSet A transformation of .
public static RedisAggregationSet<T> CloseGroup<T>(this GroupedAggregationSet<T> source){ return new RedisAggregationSet<T>(source, source.Expression);}ending
This article is just for Redis OM .NET Simple sorting of usage and usability verification . More usage and usage update reference Github
We are acting , New framework 、 New ecology
Our goal is The freedom of the 、 Easy-to-use 、 Highly malleable 、 functional 、 Robust .
So we learn from Building blocks Design concept of , Working on a new framework MASA Framework, What are its characteristics ?
- Native support Dapr, And allow Dapr Replace with traditional means of communication
- Unlimited architecture , Single application 、SOA、 Micro services support
- Support .Net Native framework , Reduce the burden of learning , In addition to the concepts that must be introduced in a specific field , Insist on not making new wheels
- Rich ecological support , In addition to the framework, there are component libraries 、 Authority Center 、 Configuration center 、 Troubleshooting center 、 A series of products such as Alarm Center
- Unit test coverage of the core code base 90%+
- Open source 、 free 、 Community driven
- What is the ? We are waiting for you , Come together and discuss
After several months of production project practice , Completed POC, At present, the previous accumulation is being refactored into new open source projects
At present, the source code has been synchronized to Github( The document site is under planning , Will gradually improve ):
QQ Group :7424099
Wechat group : Plus technology operation wechat (MasaStackTechOps), Remarks , Invite in

------ END ------
Author's brief introduction
** Ma Yue :**MASA Technical team members .
边栏推荐
- Least squares system identification class II: recursive least squares
- Niuke programming problem -- dynamic programming of must brush 101 (a thorough understanding of dynamic programming)
- [from database deletion to running] JDBC conclusion (finish the series in one day!! run as soon as you finish learning!)
- C language --- basic function realization of push box 01
- Mono 的一些实例方法
- 5g is not flat and 6G is restarted. China leads wireless communication. What is the biggest advantage of 6G?
- 【从删库到跑路】JDBC 完结篇(一天学完系列!!学完赶紧跑!)
- Find all primes less than or equal to Lim, store them in AA array, and return the number of primes
- Teach you to learn dapr - 1 The era of net developers
- Failed to upload hyperf framework using alicloud OSS
猜你喜欢

牛客编程题--必刷101之动态规划(一文彻底了解动态规划)

Sandboxed container: container or virtual machine

我把它当副业月入3万多,新手月入过万的干货分享!

Constructors and Destructors

Développer un opérateur basé sur kubebuilder (démarrer)

Memory partition model

Teach you to learn dapr - 1 The era of net developers

Arduino uno + DS1302 simple time acquisition and serial port printing

Summary of all knowledge points of C language

The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance
随机推荐
【207】Apache崩溃的几个很可能的原因,apache崩溃几个
LeetCode Algorithm 24. 两两交换链表中的节点
Niuke programming problem -- dynamic programming of must brush 101 (a thorough understanding of dynamic programming)
MS|谢黎炜组发现混合益生菌制剂及其代谢产物可缓解结肠炎
Count the number of words in a line of string and take it as the return value of the function
Overall context of concurrent programming
1-12vmware adds SSH function
[Error] ld returned 1 exit status
无需人工先验!港大&同济&LunarAI&旷视提出基于语义分组的自监督视觉表征学习,显著提升目标检测、实例分割和语义分割任务!...
[207] several possible causes of Apache crash
Multiply the values of the upper triangular elements of the array by M
当一个程序员一天被打扰 10 次,后果很惊人!
Count the number of each vowel letter in the string
Teach you to learn dapr - 9 Observability
r329(MAIX-II-A(M2A)资料汇总
Mono 的一些实例方法
Dialogue with the senior management of Chang'an Mazda, new products will be released in Q4, and space and intelligence will lead the Japanese system
5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?
Day10 daily 3 questions (3): String Matching in array
Codeforces Round #802 (Div. 2)