前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[match_phrase 查询]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
ElasticSearch
...icsearch中的match_phrase查询和span_first函数。首先,match_phrase查询可以用来指定要查询的完整字符串,如果文档中包含这个字符串,则匹配成功。其次,span_first函数可以让我们选择第一个匹配到的子串。 下面是一段使用Elasticsearch的示例代码: python GET /my_index/_search { "query": { "bool": { "should": [ { "match_phrase": { "title": { "query": "quick brown fox", "slop": 3, "max_expansions": 100 } } }, { "span_first": { "clauses": [ { "match": { "body": { "query": "brown fox", "slop": 3, "max_expansions": 100 } } } ], "end_offset": 30 } } ] } } } 在这个例子中,我们使用了一个布尔查询,其中包含了两个子查询:一个是match_phrase查询,另一个是span_first函数。match_phrase查询用于查找包含“quick brown fox”的文档,而span_first函数则用于查找包含“brown fox”的文档,并且确保其出现在“quick brown fox”之后。 四、如何优化邻近匹配性能? 除了使用Elasticsearch提供的工具外,我们还可以通过一些其他的手段来优化邻近匹配的性能。例如,我们可以增加索引缓存大小、减少搜索范围、合理设置匹配阈值等。 总的来说,Elasticsearch是一款非常强大的搜索引擎工具,它可以帮助我们快速地找到符合条件的数据。同时呢,我们还可以用上一些小窍门和方法,让邻近匹配这事儿变得更有效率、更精准,就像是给它装上了加速器和定位仪一样。希望本文的内容对你有所帮助!
2023-05-29 16:02:42
463
凌波微步_t
转载文章
...Agent,d=o.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i),l=o.match(/U3\/((\d+|\.){5,})/i),c=l&&parseInt(l[1].split(".").join(""),10)>=80,p=navigator.appVersion.match(/(iphone|ipad|ipod)/gi),s=i.devicePixelRatio||1;p||d&&d[1]>534||c||(s=1);var u=normal?1:1/s,m=r.querySelector('meta[name="viewport"]');m||(m=r.createElement("meta"),m.setAttribute("name","viewport"),r.head.appendChild(m)),m.setAttribute("content","width=device-width,user-scalable=no,initial-scale="+u+",maximum-scale="+u+",minimum-scale="+u),r.documentElement.style.fontSize=normal?"50px": a/2sn+"px"},e.exports=t["default"]}]); flex(false,100, 1);</script> 代码原理 这是阿里团队的高清方案布局代码,所谓高清方案就是利用rem的特性(我们知道默认情况下html的1rem = 16px),根据设备屏幕的DPR(设备像素比,又称DPPX,比如dpr=2时,表示1个CSS像素由4个物理像素点组成)根据设备DPR动态设置 html 的font-size为(50 dpr),同时调整页面的压缩比率(即:1/dpr),进而达到高清效果。 有何优势 引用简单,布局简便 根据设备屏幕的DPR,自动设置最合适的高清缩放。 保证了不同设备下视觉体验的一致性。(老方案是,屏幕越大元素越大;此方案是,屏幕越大,看的越多) 有效解决移动端真实1px问题(这里的1px 是设备屏幕上的物理像素) 如何使用 重要的事情说三遍! 绝不是每个地方都要用rem,rem只适用于固定尺寸! 绝不是每个地方都要用rem,rem只适用于固定尺寸! 绝不是每个地方都要用rem,rem只适用于固定尺寸! 在相当数量的布局情境中(比如底部导航元素平分屏幕宽,大尺寸元素),你必须使用百分比或者flex才能完美布局! 看过 《手机端页面自适应解决方案—rem布局》的朋友,应该对rem有所了解,这里不再赘述, 此方案也是默认 1rem = 100px,所以你布局的时候,完全可以按照设计师给你的效果图写各种尺寸啦。 比如你在效果图上量取的某个按钮元素长 55px, 宽37px ,那你直接可以这样写样式: .myBtn {width: 0.55rem;height: 0.37rem;} rem布局(进阶版)实践应用 iPhone5 下页面效果.png iPhone 6 Plus 下页面效果.png 为了让朋友们更清晰感受此方案的巨大优势,下面是源码和Demo 实践应用1(请在手机端或者手机模式下浏览效果更佳!) 实践应用2(请在手机端或者手机模式下浏览效果更佳!) 线上项目(请在手机端或者手机模式下浏览效果更佳!) 示例源码 在线Demo 常见问题说明,新手很有必要看一下(2017/1/19) 许多同学对该方案存在不少误解导致使用出现各种问题,这里统一回复下。 1.问:为啥手机网页效果图宽度是要640或者750的,我非得弄个666的不行咩? 答:老实说当然可以,不过为了规范,640或者750是相对合适的。 拿Iphone 5s 举例,它的css像素宽度是320px,由于它的dpr=2,所以它的物理像素宽度为320 × 2 = 640px,这也就是为什么,你在5s上截了一张图,在电脑上打开,它的原始宽度是640px的原因。 那 iphone 6 的截图宽度呢? 375 × 2 = 750 那 iphone 6 sp 的截图宽度呢? 414 × 3 = 1242 以此类推,你现在能明白效果图为什么一般是 640 ,750 甚至是 1242 的原因了么?(真没有歧视安卓机的意思。。。) 2.问:宽度用rem写的情况下, 在 iphone6 上没问题, 在 iphone5上会有横向滚动条,何解? 答:假设你的效果图宽度是750,在这个效果图上可能有一个宽度为7rem(高清方案默认 1rem = 100px)的元素。我们知道,高清方案的特点就是几乎完美还原效果图,也就是说,你写了一个宽度为 7rem 的元素,那么在目前主流移动设备上都是7rem。然而,iphone 5 的宽度为640,也就是6.4rem。于是横向滚动条不可避免的出现了。 怎么办呢? 这是我目前推荐的比较安全的方式:如果元素的宽度超过效果图宽度的一半(效果图宽为640或750),果断使用百分比宽度,或者flex布局。就像把等屏宽的图片宽度设为100%一样。 3.问:不是 1rem = 100px吗,为什么我的代码写了一个宽度为3rem的元素,在电脑端的谷歌浏览器上宽度只有150px? 答:先说高清方案代码,再次强调咱们的高清方案代码是根据设备的dpr动态设置html 的 font-size, 如果dpr=1(如电脑端),则html的font-size为50px,此时 1rem = 50px 如果dpr=2(如iphone 5 和 6),则html的font-size为100px,此时 1rem = 100px 如果dpr=3(如iphone 6 sp),则html的font-size为150px,此时 1rem = 150px 如果dpr为其他值,即便不是整数,如3.4 , 也是一样直接将dpr 乘以 50 。 再来说说效果图,一般来讲,我们的效果图宽度要么是640,要么是750,无论哪一个,它们对应设备的dpr=2,此时,1 rem = 50 × 2 = 100px。这也就是为什么高清方案默认1rem = 100px。而将1rem默认100px也是好处多多,可以帮你快速换算单位,比如在750宽度下的效果图,某元素宽度为53px,那么css宽度直接设为53/100=0.53rem了。 然而极少情况下,有设计师将效果图宽定为1242px,因为他手里只有一个iphone 6 sp (dpr = 3),设计完效果图刚好可以在他的iphone 6 sp里查看调整。一切完毕之后,他将这个效果图交给你来切图。由于这个效果图对应设备的dpr=3,也就是1rem = 50 × 3 = 150px。所以如果你量取了一个宽度为90px的元素,它的css宽度应该为 90/150=0.6rem。由于咱们的高清方案默认1rem=100px,为了还原效果图,你需要这样换算。当然,一个技巧就是你可以直接修改咱们的高清方案的默认设置。在代码的最后 你会看到 flex(false, 100, 1) ,将其修改成flex(false, 66.66667, 1)(感谢简友:V旅行指出此处错误! 2017/3/24)就不用那么麻烦的换算了,此时那个90px的直接写成0.9rem就可以了。 4.问:在此方案下,我如果引用了别的UI库,那些UI库的元素会显得特别小,如何解决? 答:可以这样去理解问题的原因,如果不用高清方案,别的UI库的元素在移动设备上(假设这个设备是iphone 5好了)显示是正常的,这没有问题,然后我们在这个设备上将该页面截图放到电脑上看,发现宽度是640(问答1解释过了),根据你的像素眼大致测量,你发现这个设备上的某个字体大小应该是12px,而你在电脑上测量应该是24px。 现在我们使用高清方案去还原这个页面,那么字体大小应该写为 0.24rem 才对! 所以,如果你引用了其他的UI库,为了兼容高清方案,你需要对该UI库里凡是应用px的地方做相应处理,即: a px => a0.02 rem (具体处理方式因人而异,有模块化开发经验的同学可使用类似的 px2rem 的插件去转化,也可以完全手动处理) (2017/9/9更新)然而真实情况往往更为复杂,比如,你引入了百度地图(N个样式需要处理转换);或者你引入了一个 framework;又或者你使用了 video 标签,上面默认的尺寸样式很难处理。等等这些棘手问题 面对这些情况,此时我们的高清方案如果不再压缩页面,那么以上问题将迎刃而解。 基于这样的思路,笔者对高清方案的源码做了如下修改,即添加一个叫做 normal 的参数,由它来控制页面是否压缩。 在文章顶部代码的最后,你会看到 flex(false, 100, 1),默认情况下页面是开启压缩的。 如果你需要禁止压缩,由于我们的源码执行后,直接将flex函数挂载到全局变量window上了,此时你直接在需要禁止压缩的页面执行 window.flex(true) 就可以了,而rem的用法保持不变。 有一点美中不足的是,如果禁止了页面压缩,高清屏的1像素就不能实现了,如果你必须要实现1像素,那么自行谷歌:css 0.5像素,有N多的解决方案,这里不再赘述。 5.问:有时候字体会不受控制的变大,怎么办? 答:在X5新内核Blink中,在排版页面的时候,会主动对字体进行放大,会检测页面中的主字体,当某一块字体在我们的判定规则中,认为字号较小,并且是页面中的主要字体,就会采取主动放大的操作。然而这不是我们想要的,可以采取给最大高度解决 解决方案: , :before, :after { max-height: 100000px } 补充:有同学反映,在一些情况下 textarea 标签内的字体大小即便加上上面的方案,字体也会变大,无法控制。此时你需要给 textarea 的 display 设为 table 或者 inline-table 即可恢复正常。(感谢 程序媛喵喵 对此的补充!2017/7/7) 6.问:我在底部导航用的flex感觉更合适一些,请问这样子混着用可以吗? 答:咱们的rem适合写固定尺寸。其余的根据需要换成flex或者百分比。源码示例中就有这三种的综合运用。 7.问:在高清方案下,一个标准的,较为理想的宽度为640的页面效果图应该是怎样的? 点击浏览:一个标准的640手机页面设计稿参考(没错,在此方案中,你可以完全按照这张设计稿的尺寸写布局了。就是这么简单!) 8.问:用了这个方案如何使用媒体查询呢? 一般来讲,使用了这个方案是没必要用媒体查询了,如果你必须要用,假设你要对 iphone5 (css像素宽度320px, 这里需要取其物理像素,也就是640)宽度下的类名做处理,你可以这样 @media screen and (max-width: 640px) {.yourLayout {width:100%;} } 9.问:可以提供下这个高清方案的源码吗? 'use strict';/ @param {Boolean} [normal = false] - 默认开启页面压缩以使页面高清; @param {Number} [baseFontSize = 100] - 基础fontSize, 默认100px; @param {Number} [fontscale = 1] - 有的业务希望能放大一定比例的字体;/const win = window;export default win.flex = (normal, baseFontSize, fontscale) => {const _baseFontSize = baseFontSize || 100;const _fontscale = fontscale || 1;const doc = win.document;const ua = navigator.userAgent;const matches = ua.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i);const UCversion = ua.match(/U3\/((\d+|\.){5,})/i);const isUCHd = UCversion && parseInt(UCversion[1].split('.').join(''), 10) >= 80;const isIos = navigator.appVersion.match(/(iphone|ipad|ipod)/gi);let dpr = win.devicePixelRatio || 1;if (!isIos && !(matches && matches[1] > 534) && !isUCHd) {// 如果非iOS, 非Android4.3以上, 非UC内核, 就不执行高清, dpr设为1;dpr = 1;}const scale = normal ? 1 : 1 / dpr;let metaEl = doc.querySelector('meta[name="viewport"]');if (!metaEl) {metaEl = doc.createElement('meta');metaEl.setAttribute('name', 'viewport');doc.head.appendChild(metaEl);}metaEl.setAttribute('content', width=device-width,user-scalable=no,initial-scale=${scale},maximum-scale=${scale},minimum-scale=${scale});doc.documentElement.style.fontSize = normal ? '50px' : ${_baseFontSize / 2 dpr _fontscale}px;}; 10.问:我在使用 rem 布局进阶方案的时候遇到了XXX的问题,如何解决? 此方案久经考验,具有普遍适用性,自身出致命问题的情况很少,至少笔者是没遇到过。 绝大多数你遇到的问题,都是由于对rem布局理解不到位导致的。本文对rem布局做了大量的解释说明,配置了若干 demo,你可以把你遇到的问题放到demo里测试。遇到问题时,首先问自己,为什么这明显的错误大家没遇到就我遇到了?? 如果你真的经过充分验证,比对,确实是rem布局自身出了问题,那么请私信我,把还原问题场景的 demo 或者文件发给我。谢谢! 本篇文章为转载内容。原文链接:https://blog.csdn.net/hjhfreshman/article/details/88864894。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-03-23 12:01:53
133
转载
Python
...字符出现0次或多次 match = re.search(pattern, text) if match: print("Found:", match.group()) else: print("No match found.") 上述代码中,Pyt.on就是一个简单的模糊匹配模式,其中.代表任何单个字符,表示前面元素可以重复任意次(包括0次),因此可以匹配到"Python"。 3. Levenshtein距离与fuzzywuzzy库 除了正则表达式,Python还有一个更为直观且计算能力强悍的模糊匹配工具——fuzzywuzzy库,它基于Levenshtein距离算法来衡量两个字符串之间的相似度: python from fuzzywuzzy import fuzz str1 = "Python" str2 = "Pithon" ratio = fuzz.ratio(str1, str2) print(f"Similarity ratio: {ratio}%") 输出结果: Similarity ratio: 80% 在这个例子中,尽管str2比str1少了一个字母'h',但它们的相似度仍然高达80%,这就是模糊匹配的魅力所在。 4. 使用difflib模块进行序列比较 Python内置的difflib模块也能进行模糊匹配,尤其擅长于找出序列(如字符串列表)中最相似的元素: python import difflib words_list = ['python', 'perl', 'ruby', 'javascript'] target_word = 'pyton' matcher = difflib.get_close_matches(target_word, words_list) print(matcher) 输出结果: ['python'] 这段代码展示了如何找到与目标词最接近的实际存在的词汇。 5. 结语 模糊匹配的应用与思考 通过以上实例,我们对Python的模糊匹配有了初步了解。其实,模糊匹配这门技术,在咱们日常生活中不少场景都派上大用场啦,比如文本纠错、搜索引擎还有数据分析这些领域,它都有广泛的应用和实实在在的帮助呢!在使用过程中,我们需要根据实际场景灵活运用不同方法,甚至有时候还需要结合多种策略以达到最佳效果。每一次成功的模糊匹配背后,都体现了Python作为一门人性化语言的智慧和温度。记住了啊,甭管啥时候在哪儿,让咱们编的程序更能揣摩用户的心思,更加接纳用户的意图,这可是编程大业中的关键追求之一!
2023-07-29 12:15:00
280
柳暗花明又一村
JQuery
...明,对于简单的DOM查询与操作,原生JavaScript在速度上已经不逊于甚至超越了许多流行的库(如jQuery),这鼓励更多开发者回归原生API以优化性能。同时,诸如Sizzle等独立的选择器引擎项目,不仅为jQuery提供支持,也能被其他库或框架集成,提高了跨平台和跨项目的兼容性及效率。 此外,考虑到现代浏览器对ES6及以上版本特性的广泛支持,如箭头函数、let/const声明以及模板字符串等,使得直接使用JavaScript进行DOM操作更为简洁高效。例如,利用“Node.matches()”方法配合CSS选择器,可以实现与jQuery类似的元素筛选功能,且具备良好的浏览器兼容性。 综上所述,尽管jQuery在简化DOM操作方面曾发挥巨大作用,但随着JavaScript生态的发展,理解和掌握原生API及其最佳实践已成为现代前端开发者的重要技能之一。了解和对比不同选择器方案的优缺点,并结合实际应用场景灵活运用,有助于我们构建更为快速、轻量级的Web应用。
2023-06-13 17:39:52
322
软件工程师
Datax
...,我们首先通过SQL查询获取到表中的所有非空行,然后将这些行插入到目标表中。这样,我们就避免了数据的重复插入。 三、Datax的数据验证 在数据传输过程中,我们还需要进行数据验证,以确保数据的正确性。例如,我们可以通过校验数据是否满足某种规则,来判断数据的有效性。 以下是一个简单的数据校验的例子: java public boolean isValid(String data) { return Pattern.matches("\\d{3}-\\d{8}", data); } 在这个例子中,我们定义了一个正则表达式,用于匹配手机号码。如果输入的数据恰好符合我们设定的这个正则表达式的规矩,那咱就可以拍着胸脯说,这个数据是完全OK的,是有效的。 四、Datax的数据清洗 在数据传输的过程中,我们还可能会遇到一些异常情况,如数据丢失、数据损坏等。在这种情况下,我们需要对数据进行清洗,以恢复数据的完整性和一致性。 以下是一个简单的数据清洗的例子: java public void cleanUp(EnvContext envContext) { String sql = "UPDATE table SET column1 = NULL WHERE column2 = 'error'"; SqlRunner.run(sql, DatabaseType.H2); } 在这个例子中,我们通过SQL语句,将表中column2为'error'的所有记录的column1字段设为NULL。这样,我们就清除了这些异常数据的影响。 五、结论 在使用Datax进行数据处理时,我们需要关注数据的质量、正确性和完整性等问题。通过严谨地给数据“体检”、反复验证其真实性,再仔仔细细地给它“洗个澡”,我们就能确保数据的准确度和可靠性蹭蹭上涨,真正做到让数据靠谱起来。同时呢,我们也要持续地改进咱们的数据处理方法,好让它们能灵活适应各种不断变化的数据环境,跟上时代步伐。
2023-05-23 08:20:57
281
柳暗花明又一村-t
Mongo
...用新的模式进行匹配 match = new_pattern.search(line) if match: print(match.group(1)) 4. 如何预防日志文件格式的变化? 虽然我们不能完全控制MongoDB内部的日志格式变化,但我们可以通过以下方式减少因格式变化带来的影响: - 定期备份:确保定期备份你的日志文件,这样即使发生意外,你也可以恢复到之前的状态。 - 监控变更:关注MongoDB社区和官方论坛,了解最新的版本变化,特别是那些可能影响日志格式的更改。 - 自动化测试:建立一套自动化测试系统,定期检查你的日志解析脚本是否仍然有效。 5. 结语 最后,我想说的是,尽管MongoDB的日志文件格式不兼容问题可能看起来很小,但它确实能给开发工作带来不便。不过,只要我们做好准备,采取适当的措施,就能有效地应对这类问题。希望今天的分享对你有所帮助,如果你有任何疑问或想了解更多细节,请随时留言讨论! --- 以上就是我关于“MongoDB的日志文件格式不兼容问题”的全部内容。希望这篇文章能够让你在面对类似问题时更加从容。如果有任何建议或反馈,欢迎随时告诉我!
2024-11-21 15:43:58
82
人生如戏
转载文章
...laim that matches the specified predicate. See the “Applying Claims” section for an example predicate. 如果用户含有与指定谓词匹配的声明(Claim)时,返回true。参见“运用声明(Claims)”中的示例谓词 RemoveClaim(claim) Removes a claim from the user identity. 删除用户的声明(Claim)。 Other members are available, but the ones in the table are those that are used most often in web applications, for reason that will become obvious as I demonstrate how claims fit into the wider ASP.NET platform. 还有一些可用的其它成员,但表中的这些是在Web应用程序中最常用的,随着我演示如何将声明(Claims)融入更宽泛的ASP.NET平台,它们为什么最常用就很显然了。 In Listing 15-12, I cast the IIdentity implementation to the ClaimsIdentity type and pass the enumeration of Claim objects returned by the ClaimsIdentity.Claims property to the View method. A Claim object represents a single piece of data about the user, and the Claim class defines the properties shown in Table 15-6. 在清单15-12中,我将IIdentity实现转换成了ClaimsIdentity类型,并且给View方法传递了ClaimsIdentity.Claims属性所返回的Claim对象的枚举。Claim对象所示表示的是关于用户的一个单一的数据片段,Claim类定义的属性如表15-6所示。 Table 15-6. The Properties Defined by the Claim Class 表15-6. Claim类定义的属性 Name 名称 Description 描述 Issuer Returns the name of the system that provided the claim 返回提供声明(Claim)的系统名称 Subject Returns the ClaimsIdentity object for the user who the claim refers to 返回声明(Claim)所指用户的ClaimsIdentity对象 Type Returns the type of information that the claim represents 返回声明(Claim)所表示的信息类型 Value Returns the piece of information that the claim represents 返回声明(Claim)所表示的信息片段 Listing 15-13 shows the contents of the Index.cshtml file that I created in the Views/Claims folder and that is rendered by the Index action of the Claims controller. The view adds a row to a table for each claim about the user. 清单15-13显示了我在Views/Claims文件夹中创建的Index.cshtml文件的内容,它由Claims控制器中的Index动作方法进行渲染。该视图为用户的每项声明(Claim)添加了一个表格行。 Listing 15-13. The Contents of the Index.cshtml File in the Views/Claims Folder 清单15-13. Views/Claims文件夹中Index.cshtml文件的内容 @using System.Security.Claims@using Users.Infrastructure@model IEnumerable<Claim>@{ ViewBag.Title = "Claims"; }<div class="panel panel-primary"><div class="panel-heading">Claims</div><table class="table table-striped"><tr><th>Subject</th><th>Issuer</th><th>Type</th><th>Value</th></tr>@foreach (Claim claim in Model.OrderBy(x => x.Type)) {<tr><td>@claim.Subject.Name</td><td>@claim.Issuer</td><td>@Html.ClaimType(claim.Type)</td><td>@claim.Value</td></tr>}</table></div> The value of the Claim.Type property is a URI for a Microsoft schema, which isn’t especially useful. The popular schemas are used as the values for fields in the System.Security.Claims.ClaimTypes class, so to make the output from the Index.cshtml view easier to read, I added an HTML helper to the IdentityHelpers.cs file, as shown in Listing 15-14. It is this helper that I use in the Index.cshtml file to format the value of the Claim.Type property. Claim.Type属性的值是一个微软模式(Microsoft Schema)的URI(统一资源标识符),这是特别有用的。System.Security.Claims.ClaimTypes类中字段的值使用的是流行模式(Popular Schema),因此为了使Index.cshtml视图的输出更易于阅读,我在IdentityHelpers.cs文件中添加了一个HTML辅助器,如清单15-14所示。Index.cshtml文件正是使用这个辅助器格式化了Claim.Type属性的值。 Listing 15-14. Adding a Helper to the IdentityHelpers.cs File 清单15-14. 在IdentityHelpers.cs文件中添加辅助器 using System.Web;using System.Web.Mvc;using Microsoft.AspNet.Identity.Owin;using System;using System.Linq;using System.Reflection;using System.Security.Claims;namespace Users.Infrastructure {public static class IdentityHelpers {public static MvcHtmlString GetUserName(this HtmlHelper html, string id) {AppUserManager mgr= HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();return new MvcHtmlString(mgr.FindByIdAsync(id).Result.UserName);} public static MvcHtmlString ClaimType(this HtmlHelper html, string claimType) {FieldInfo[] fields = typeof(ClaimTypes).GetFields();foreach (FieldInfo field in fields) {if (field.GetValue(null).ToString() == claimType) {return new MvcHtmlString(field.Name);} }return new MvcHtmlString(string.Format("{0}",claimType.Split('/', '.').Last()));} }} Note The helper method isn’t at all efficient because it reflects on the fields of the ClaimType class for each claim that is displayed, but it is sufficient for my purposes in this chapter. You won’t often need to display the claim type in real applications. 注:该辅助器并非十分有效,因为它只是针对每个要显示的声明(Claim)映射出ClaimType类的字段,但对我要的目的已经足够了。在实际项目中不会经常需要显示声明(Claim)的类型。 To see why I have created a controller that uses claims without really explaining what they are, start the application, authenticate as the user Alice (with the password MySecret), and request the /Claims/Index URL. Figure 15-5 shows the content that is generated. 为了弄明白我为何要先创建一个使用声明(Claims)的控制器,而没有真正解释声明(Claims)是什么的原因,可以启动应用程序,以用户Alice进行认证(其口令是MySecret),并请求/Claims/Index URL。图15-5显示了生成的内容。 Figure 15-5. The output from the Index action of the Claims controller 图15-5. Claims控制器中Index动作的输出 It can be hard to make out the detail in the figure, so I have reproduced the content in Table 15-7. 这可能还难以认识到此图的细节,为此我在表15-7中重列了其内容。 Table 15-7. The Data Shown in Figure 15-5 表15-7. 图15-5中显示的数据 Subject(科目) Issuer(发行者) Type(类型) Value(值) Alice LOCAL AUTHORITY SecurityStamp Unique ID Alice LOCAL AUTHORITY IdentityProvider ASP.NET Identity Alice LOCAL AUTHORITY Role Employees Alice LOCAL AUTHORITY Role Users Alice LOCAL AUTHORITY Name Alice Alice LOCAL AUTHORITY NameIdentifier Alice’s user ID The table shows the most important aspect of claims, which is that I have already been using them when I implemented the traditional authentication and authorization features in Chapter 14. You can see that some of the claims relate to user identity (the Name claim is Alice, and the NameIdentifier claim is Alice’s unique user ID in my ASP.NET Identity database). 此表展示了声明(Claims)最重要的方面,这些是我在第14章中实现传统的认证和授权特性时,一直在使用的信息。可以看出,有些声明(Claims)与用户标识有关(Name声明是Alice,NameIdentifier声明是Alice在ASP.NET Identity数据库中的唯一用户ID号)。 Other claims show membership of roles—there are two Role claims in the table, reflecting the fact that Alice is assigned to both the Users and Employees roles. There is also a claim about how Alice has been authenticated: The IdentityProvider is set to ASP.NET Identity. 其他声明(Claims)显示了角色成员——表中有两个Role声明(Claim),体现出Alice被赋予了Users和Employees两个角色这一事实。还有一个是Alice已被认证的声明(Claim):IdentityProvider被设置到了ASP.NET Identity。 The difference when this information is expressed as a set of claims is that you can determine where the data came from. The Issuer property for all the claims shown in the table is set to LOCAL AUTHORITY, which indicates that the user’s identity has been established by the application. 当这种信息被表示成一组声明(Claims)时的差别是,你能够确定这些数据是从哪里来的。表中所显示的所有声明的Issuer属性(发布者)都被设置到了LOACL AUTHORITY(本地授权),这说明该用户的标识是由应用程序建立的。 So, now that you have seen some example claims, I can more easily describe what a claim is. A claim is any piece of information about a user that is available to the application, including the user’s identity and role memberships. And, as you have seen, the information I have been defining about my users in earlier chapters is automatically made available as claims by ASP.NET Identity. 因此,现在你已经看到了一些声明(Claims)示例,我可以更容易地描述声明(Claim)是什么了。一项声明(Claim)是可用于应用程序中的有关用户的一个信息片段,包括用户的标识以及角色成员等。而且,正如你所看到的,我在前几章定义的关于用户的信息,被ASP.NET Identity自动地作为声明(Claims)了。 15.3.2 Creating and Using Claims 15.3.2 创建和使用声明(Claims) Claims are interesting for two reasons. The first reason is that an application can obtain claims from multiple sources, rather than just relying on a local database for information about the user. You will see a real example of this when I show you how to authenticate users through a third-party system in the “Using Third-Party Authentication” section, but for the moment I am going to add a class to the example project that simulates a system that provides claims information. Listing 15-15 shows the contents of the LocationClaimsProvider.cs file that I added to the Infrastructure folder. 声明(Claims)比较有意思的原因有两个。第一个原因是应用程序可以从多个来源获取声明(Claims),而不是只能依靠本地数据库关于用户的信息。你将会看到一个实际的示例,在“使用第三方认证”小节中,将演示如何通过第三方系统来认证用户。不过,此刻我只打算在示例项目中添加一个类,用以模拟一个提供声明(Claims)信息的系统。清单15-15显示了我添加到Infrastructure文件夹中LocationClaimsProvider.cs文件的内容。 Listing 15-15. The Contents of the LocationClaimsProvider.cs File 清单15-15. LocationClaimsProvider.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public static class LocationClaimsProvider {public static IEnumerable<Claim> GetClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.Name.ToLower() == "alice") {claims.Add(CreateClaim(ClaimTypes.PostalCode, "DC 20500"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "DC"));} else {claims.Add(CreateClaim(ClaimTypes.PostalCode, "NY 10036"));claims.Add(CreateClaim(ClaimTypes.StateOrProvince, "NY"));}return claims;}private static Claim CreateClaim(string type, string value) {return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");} }} The GetClaims method takes a ClaimsIdentity argument and uses the Name property to create claims about the user’s ZIP code and state. This class allows me to simulate a system such as a central HR database, which would be the authoritative source of location information about staff, for example. GetClaims方法以ClaimsIdentity为参数,并使用Name属性创建了关于用户ZIP码(邮政编码)和州府的声明(Claims)。上述这个类使我能够模拟一个诸如中心化的HR数据库(人力资源数据库)之类的系统,它可能会成为全体职员的地点信息的权威数据源。 Claims are associated with the user’s identity during the authentication process, and Listing 15-16 shows the changes I made to the Login action method of the Account controller to call the LocationClaimsProvider class. 在认证过程期间,声明(Claims)是与用户标识关联在一起的,清单15-16显示了我对Account控制器中Login动作方法所做的修改,以便调用LocationClaimsProvider类。 Listing 15-16. Associating Claims with a User in the AccountController.cs File 清单15-16. AccountController.cs文件中用户用声明的关联 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... You can see the effect of the location claims by starting the application, authenticating as a user, and requesting the /Claim/Index URL. Figure 15-6 shows the claims for Alice. You may have to sign out and sign back in again to see the change. 为了看看这个地点声明(Claims)的效果,可以启动应用程序,以一个用户进行认证,并请求/Claim/Index URL。图15-6显示了Alice的声明(Claims)。你可能需要退出,然后再次登录才会看到发生的变化。 Figure 15-6. Defining additional claims for users 图15-6. 定义用户的附加声明 Obtaining claims from multiple locations means that the application doesn’t have to duplicate data that is held elsewhere and allows integration of data from external parties. The Claim.Issuer property tells you where a claim originated from, which helps you judge how accurate the data is likely to be and how much weight you should give the data in your application. Location data obtained from a central HR database is likely to be more accurate and trustworthy than data obtained from an external mailing list provider, for example. 从多个地点获取声明(Claims)意味着应用程序不必复制其他地方保持的数据,并且能够与外部的数据集成。Claim.Issuer属性(图15-6中的Issuer数据列——译者注)能够告诉你一个声明(Claim)的发源地,这有助于让你判断数据的精确程度,也有助于让你决定这类数据在应用程序中的权重。例如,从中心化的HR数据库获取的地点数据可能要比外部邮件列表提供器获取的数据更为精确和可信。 1. Applying Claims 1. 运用声明(Claims) The second reason that claims are interesting is that you can use them to manage user access to your application more flexibly than with standard roles. The problem with roles is that they are static, and once a user has been assigned to a role, the user remains a member until explicitly removed. This is, for example, how long-term employees of big corporations end up with incredible access to internal systems: They are assigned the roles they require for each new job they get, but the old roles are rarely removed. (The unexpectedly broad systems access sometimes becomes apparent during the investigation into how someone was able to ship the contents of the warehouse to their home address—true story.) 声明(Claims)有意思的第二个原因是,你可以用它们来管理用户对应用程序的访问,这要比标准的角色管理更为灵活。角色的问题在于它们是静态的,而且一旦用户已经被赋予了一个角色,该用户便是一个成员,直到明确地删除为止。例如,这意味着大公司的长期雇员,对内部系统的访问会十分惊人:他们每次在获得新工作时,都会赋予所需的角色,但旧角色很少被删除。(在调查某人为何能够将仓库里的东西发往他的家庭地址过程中发现,有时会出现异常宽泛的系统访问——真实的故事) Claims can be used to authorize users based directly on the information that is known about them, which ensures that the authorization changes when the data changes. The simplest way to do this is to generate Role claims based on user data that are then used by controllers to restrict access to action methods. Listing 15-17 shows the contents of the ClaimsRoles.cs file that I added to the Infrastructure. 声明(Claims)可以直接根据用户已知的信息对用户进行授权,这能够保证当数据发生变化时,授权也随之而变。此事最简单的做法是根据用户数据来生成Role声明(Claim),然后由控制器用来限制对动作方法的访问。清单15-17显示了我添加到Infrastructure中的ClaimsRoles.cs文件的内容。 Listing 15-17. The Contents of the ClaimsRoles.cs File 清单15-17. ClaimsRoles.cs文件的内容 using System.Collections.Generic;using System.Security.Claims; namespace Users.Infrastructure {public class ClaimsRoles {public static IEnumerable<Claim> CreateRolesFromClaims(ClaimsIdentity user) {List<Claim> claims = new List<Claim>();if (user.HasClaim(x => x.Type == ClaimTypes.StateOrProvince&& x.Issuer == "RemoteClaims" && x.Value == "DC")&& user.HasClaim(x => x.Type == ClaimTypes.Role&& x.Value == "Employees")) {claims.Add(new Claim(ClaimTypes.Role, "DCStaff"));}return claims;} }} The gnarly looking CreateRolesFromClaims method uses lambda expressions to determine whether the user has a StateOrProvince claim from the RemoteClaims issuer with a value of DC and a Role claim with a value of Employees. If the user has both claims, then a Role claim is returned for the DCStaff role. Listing 15-18 shows how I call the CreateRolesFromClaims method from the Login action in the Account controller. CreateRolesFromClaims是一个粗糙的考察方法,它使用了Lambda表达式,以检查用户是否具有StateOrProvince声明(Claim),该声明来自于RemoteClaims发行者(Issuer),值为DC。也检查用户是否具有Role声明(Claim),其值为Employees。如果用户这两个声明都有,那么便返回一个DCStaff角色的Role声明。清单15-18显示了如何在Account控制器中的Login动作中调用CreateRolesFromClaims方法。 Listing 15-18. Generating Roles Based on Claims in the AccountController.cs File 清单15-18. 在AccountController.cs中根据声明生成角色 ...[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(LocationClaimsProvider.GetClaims(ident)); ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);}... I can then restrict access to an action method based on membership of the DCStaff role. Listing 15-19 shows a new action method I added to the Claims controller to which I have applied the Authorize attribute. 然后我可以根据DCStaff角色的成员,来限制对一个动作方法的访问。清单15-19显示了在Claims控制器中添加的一个新的动作方法,在该方法上已经运用了Authorize注解属性。 Listing 15-19. Adding a New Action Method to the ClaimsController.cs File 清单15-19. 在ClaimsController.cs文件中添加一个新的动作方法 using System.Security.Claims;using System.Web;using System.Web.Mvc;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [Authorize(Roles="DCStaff")]public string OtherAction() {return "This is the protected action";} }} Users will be able to access OtherAction only if their claims grant them membership to the DCStaff role. Membership of this role is generated dynamically, so a change to the user’s employment status or location information will change their authorization level. 只要用户的声明(Claims)承认他们是DCStaff角色的成员,那么他们便能访问OtherAction动作。该角色的成员是动态生成的,因此,若是用户的雇用状态或地点信息发生变化,也会改变他们的授权等级。 提示:请读者从这个例子中吸取其中的思想精髓。对于读物的理解程度,仁者见仁,智者见智,能领悟多少,全凭各人,译者感觉这里的思想有无数的可能。举例说明:(1)可以根据用户的身份进行授权,比如学生在校时是“学生”,毕业后便是“校友”;(2)可以根据用户所处的部门进行授权,人事部用户属于人事团队,销售部用户属于销售团队,各团队有其自己的应用;(3)下一小节的示例是根据用户的地点授权。简言之:一方面用户的各种声明(Claim)都可以用来进行授权;另一方面用户的声明(Claim)又是可以自定义的。于是可能的运用就无法估计了。总之一句话,这种基于声明的授权(Claims-Based Authorization)有无限可能!要是没有我这里的提示,是否所有读者在此处都会有所体会?——译者注 15.3.3 Authorizing Access Using Claims 15.3.3 使用声明(Claims)授权访问 The previous example is an effective demonstration of how claims can be used to keep authorizations fresh and accurate, but it is a little indirect because I generate roles based on claims data and then enforce my authorization policy based on the membership of that role. A more direct and flexible approach is to enforce authorization directly by creating a custom authorization filter attribute. Listing 15-20 shows the contents of the ClaimsAccessAttribute.cs file, which I added to the Infrastructure folder and used to create such a filter. 前面的示例有效地演示了如何用声明(Claims)来保持新鲜和准确的授权,但有点不太直接,因为我要根据声明(Claims)数据来生成了角色,然后强制我的授权策略基于角色成员。一个更直接且灵活的办法是直接强制授权,其做法是创建一个自定义的授权过滤器注解属性。清单15-20演示了ClaimsAccessAttribute.cs文件的内容,我将它添加在Infrastructure文件夹中,并用它创建了这种过滤器。 Listing 15-20. The Contents of the ClaimsAccessAttribute.cs File 清单15-20. ClaimsAccessAttribute.cs文件的内容 using System.Security.Claims;using System.Web;using System.Web.Mvc; namespace Users.Infrastructure {public class ClaimsAccessAttribute : AuthorizeAttribute {public string Issuer { get; set; }public string ClaimType { get; set; }public string Value { get; set; }protected override bool AuthorizeCore(HttpContextBase context) {return context.User.Identity.IsAuthenticated&& context.User.Identity is ClaimsIdentity&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>x.Issuer == Issuer && x.Type == ClaimType && x.Value == Value);} }} The attribute I have defined is derived from the AuthorizeAttribute class, which makes it easy to create custom authorization policies in MVC framework applications by overriding the AuthorizeCore method. My implementation grants access if the user is authenticated, the IIdentity implementation is an instance of ClaimsIdentity, and the user has a claim with the issuer, type, and value matching the class properties. Listing 15-21 shows how I applied the attribute to the Claims controller to authorize access to the OtherAction method based on one of the location claims created by the LocationClaimsProvider class. 我所定义的这个注解属性派生于AuthorizeAttribute类,通过重写AuthorizeCore方法,很容易在MVC框架应用程序中创建自定义的授权策略。在这个实现中,若用户是已认证的、其IIdentity实现是一个ClaimsIdentity实例,而且该用户有一个带有issuer、type以及value的声明(Claim),它们与这个类的属性是匹配的,则该用户便是允许访问的。清单15-21显示了如何将这个注解属性运用于Claims控制器,以便根据LocationClaimsProvider类创建的地点声明(Claim),对OtherAction方法进行授权访问。 Listing 15-21. Performing Authorization on Claims in the ClaimsController.cs File 清单15-21. 在ClaimsController.cs文件中执行基于声明的授权 using System.Security.Claims;using System.Web;using System.Web.Mvc;using Users.Infrastructure;namespace Users.Controllers {public class ClaimsController : Controller {[Authorize]public ActionResult Index() {ClaimsIdentity ident = HttpContext.User.Identity as ClaimsIdentity;if (ident == null) {return View("Error", new string[] { "No claims available" });} else {return View(ident.Claims);} } [ClaimsAccess(Issuer="RemoteClaims", ClaimType=ClaimTypes.PostalCode,Value="DC 20500")]public string OtherAction() {return "This is the protected action";} }} My authorization filter ensures that only users whose location claims specify a ZIP code of DC 20500 can invoke the OtherAction method. 这个授权过滤器能够确保只有地点声明(Claim)的邮编为DC 20500的用户才能请求OtherAction方法。 15.4 Using Third-Party Authentication 15.4 使用第三方认证 One of the benefits of a claims-based system such as ASP.NET Identity is that any of the claims can come from an external system, even those that identify the user to the application. This means that other systems can authenticate users on behalf of the application, and ASP.NET Identity builds on this idea to make it simple and easy to add support for authenticating users through third parties such as Microsoft, Google, Facebook, and Twitter. 基于声明的系统,如ASP.NET Identity,的好处之一是任何声明都可以来自于外部系统,即使是将用户标识到应用程序的那些声明。这意味着其他系统可以代表应用程序来认证用户,而ASP.NET Identity就建立在这样的思想之上,使之能够简单而方便地添加第三方认证用户的支持,如微软、Google、Facebook、Twitter等。 There are some substantial benefits of using third-party authentication: Many users will already have an account, users can elect to use two-factor authentication, and you don’t have to manage user credentials in the application. In the sections that follow, I’ll show you how to set up and use third-party authentication for Google users, which Table 15-8 puts into context. 使用第三方认证有一些实际的好处:许多用户已经有了账号、用户可以选择使用双因子认证、你不必在应用程序中管理用户凭据等等。在以下小节中,我将演示如何为Google用户建立并使用第三方认证,表15-8描述了事情的情形。 Table 15-8. Putting Third-Party Authentication in Context 表15-8. 第三方认证情形 Question 问题 Answer 回答 What is it? 什么是第三方认证? Authenticating with third parties lets you take advantage of the popularity of companies such as Google and Facebook. 第三方认证使你能够利用流行公司,如Google和Facebook,的优势。 Why should I care? 为何要关心它? Users don’t like having to remember passwords for many different sites. Using a provider with large-scale adoption can make your application more appealing to users of the provider’s services. 用户不喜欢记住许多不同网站的口令。使用大范围适应的提供器可使你的应用程序更吸引有提供器服务的用户。 How is it used by the MVC framework? 如何在MVC框架中使用它? This feature isn’t used directly by the MVC framework. 这不是一个直接由MVC框架使用的特性。 Note The reason I have chosen to demonstrate Google authentication is that it is the only option that doesn’t require me to register my application with the authentication service. You can get details of the registration processes required at http://bit.ly/1cqLTrE. 提示:我选择演示Google认证的原因是,它是唯一不需要在其认证服务中注册我应用程序的公司。有关认证服务注册过程的细节,请参阅http://bit.ly/1cqLTrE。 15.4.1 Enabling Google Authentication 15.4.1 启用Google认证 ASP.NET Identity comes with built-in support for authenticating users through their Microsoft, Google, Facebook, and Twitter accounts as well more general support for any authentication service that supports OAuth. The first step is to add the NuGet package that includes the Google-specific additions for ASP.NET Identity. Enter the following command into the Package Manager Console: ASP.NET Identity带有通过Microsoft、Google、Facebook以及Twitter账号认证用户的内建支持,并且对于支持OAuth的认证服务具有更普遍的支持。第一个步骤是添加NuGet包,包中含有用于ASP.NET Identity的Google专用附件。请在“Package Manager Console(包管理器控制台)”中输入以下命令: Install-Package Microsoft.Owin.Security.Google -version 2.0.2 There are NuGet packages for each of the services that ASP.NET Identity supports, as described in Table 15-9. 对于ASP.NET Identity支持的每一种服务都有相应的NuGet包,如表15-9所示。 Table 15-9. The NuGet Authenticaton Packages 表15-9. NuGet认证包 Name 名称 Description 描述 Microsoft.Owin.Security.Google Authenticates users with Google accounts 用Google账号认证用户 Microsoft.Owin.Security.Facebook Authenticates users with Facebook accounts 用Facebook账号认证用户 Microsoft.Owin.Security.Twitter Authenticates users with Twitter accounts 用Twitter账号认证用户 Microsoft.Owin.Security.MicrosoftAccount Authenticates users with Microsoft accounts 用Microsoft账号认证用户 Microsoft.Owin.Security.OAuth Authenticates users against any OAuth 2.0 service 根据任一OAuth 2.0服务认证用户 Once the package is installed, I enable support for the authentication service in the OWIN startup class, which is defined in the App_Start/IdentityConfig.cs file in the example project. Listing 15-22 shows the change that I have made. 一旦安装了这个包,便可以在OWIN启动类中启用此项认证服务的支持,启动类的定义在示例项目的App_Start/IdentityConfig.cs文件中。清单15-22显示了所做的修改。 Listing 15-22. Enabling Google Authentication in the IdentityConfig.cs File 清单15-22. 在IdentityConfig.cs文件中启用Google认证 using Microsoft.AspNet.Identity;using Microsoft.Owin;using Microsoft.Owin.Security.Cookies;using Owin;using Users.Infrastructure;using Microsoft.Owin.Security.Google;namespace Users {public class IdentityConfig {public void Configuration(IAppBuilder app) {app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),}); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);app.UseGoogleAuthentication();} }} Each of the packages that I listed in Table 15-9 contains an extension method that enables the corresponding service. The extension method for the Google service is called UseGoogleAuthentication, and it is called on the IAppBuilder implementation that is passed to the Configuration method. 表15-9所列的每个包都含有启用相应服务的扩展方法。用于Google服务的扩展方法名称为UseGoogleAuthentication,它通过传递给Configuration方法的IAppBuilder实现进行调用。 Next I added a button to the Views/Account/Login.cshtml file, which allows users to log in via Google. You can see the change in Listing 15-23. 下一步骤是在Views/Account/Login.cshtml文件中添加一个按钮,让用户能够通过Google进行登录。所做的修改如清单15-23所示。 Listing 15-23. Adding a Google Login Button to the Login.cshtml File 清单15-23. 在Login.cshtml文件中添加Google登录按钮 @model Users.Models.LoginModel@{ ViewBag.Title = "Login";}<h2>Log In</h2> @Html.ValidationSummary()@using (Html.BeginForm()) {@Html.AntiForgeryToken();<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><div class="form-group"><label>Name</label>@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })</div><div class="form-group"><label>Password</label>@Html.PasswordFor(x => x.Password, new { @class = "form-control" })</div><button class="btn btn-primary" type="submit">Log In</button>}@using (Html.BeginForm("GoogleLogin", "Account")) {<input type="hidden" name="returnUrl" value="@ViewBag.returnUrl" /><button class="btn btn-primary" type="submit">Log In via Google</button>} The new button submits a form that targets the GoogleLogin action on the Account controller. You can see this method—and the other changes I made the controller—in Listing 15-24. 新按钮递交一个表单,目标是Account控制器中的GoogleLogin动作。可从清单15-24中看到该方法,以及在控制器中所做的其他修改。 Listing 15-24. Adding Support for Google Authentication to the AccountController.cs File 清单15-24. 在AccountController.cs文件中添加Google认证支持 using System.Threading.Tasks;using System.Web.Mvc;using Users.Models;using Microsoft.Owin.Security;using System.Security.Claims;using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;using Users.Infrastructure;using System.Web; namespace Users.Controllers {[Authorize]public class AccountController : Controller {[AllowAnonymous]public ActionResult Login(string returnUrl) {if (HttpContext.User.Identity.IsAuthenticated) {return View("Error", new string[] { "Access Denied" });}ViewBag.returnUrl = returnUrl;return View();}[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Login(LoginModel details, string returnUrl) {if (ModelState.IsValid) {AppUser user = await UserManager.FindAsync(details.Name,details.Password);if (user == null) {ModelState.AddModelError("", "Invalid name or password.");} else {ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); ident.AddClaims(LocationClaimsProvider.GetClaims(ident));ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident)); AuthManager.SignOut();AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false}, ident);return Redirect(returnUrl);} }ViewBag.returnUrl = returnUrl;return View(details);} [HttpPost][AllowAnonymous]public ActionResult GoogleLogin(string returnUrl) {var properties = new AuthenticationProperties {RedirectUri = Url.Action("GoogleLoginCallback",new { returnUrl = returnUrl})};HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();}[AllowAnonymous]public async Task<ActionResult> GoogleLoginCallback(string returnUrl) {ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();AppUser user = await UserManager.FindAsync(loginInfo.Login);if (user == null) {user = new AppUser {Email = loginInfo.Email,UserName = loginInfo.DefaultUserName,City = Cities.LONDON, Country = Countries.UK};IdentityResult result = await UserManager.CreateAsync(user);if (!result.Succeeded) {return View("Error", result.Errors);} else {result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);if (!result.Succeeded) {return View("Error", result.Errors);} }}ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties {IsPersistent = false }, ident);return Redirect(returnUrl ?? "/");}[Authorize]public ActionResult Logout() {AuthManager.SignOut();return RedirectToAction("Index", "Home");}private IAuthenticationManager AuthManager {get {return HttpContext.GetOwinContext().Authentication;} }private AppUserManager UserManager {get {return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();} }} } The GoogleLogin method creates an instance of the AuthenticationProperties class and sets the RedirectUri property to a URL that targets the GoogleLoginCallback action in the same controller. The next part is a magic phrase that causes ASP.NET Identity to respond to an unauthorized error by redirecting the user to the Google authentication page, rather than the one defined by the application: GoogleLogin方法创建了AuthenticationProperties类的一个实例,并为RedirectUri属性设置了一个URL,其目标为同一控制器中的GoogleLoginCallback动作。下一个部分是一个神奇阶段,通过将用户重定向到Google认证页面,而不是应用程序所定义的认证页面,让ASP.NET Identity对未授权的错误进行响应: ...HttpContext.GetOwinContext().Authentication.Challenge(properties, "Google");return new HttpUnauthorizedResult();... This means that when the user clicks the Log In via Google button, their browser is redirected to the Google authentication service and then redirected back to the GoogleLoginCallback action method once they are authenticated. 这意味着,当用户通过点击Google按钮进行登录时,浏览器被重定向到Google的认证服务,一旦在那里认证之后,便被重定向回GoogleLoginCallback动作方法。 I get details of the external login by calling the GetExternalLoginInfoAsync of the IAuthenticationManager implementation, like this: 我通过调用IAuthenticationManager实现的GetExternalLoginInfoAsync方法,我获得了外部登录的细节,如下所示: ...ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();... The ExternalLoginInfo class defines the properties shown in Table 15-10. ExternalLoginInfo类定义的属性如表15-10所示: Table 15-10. The Properties Defined by the ExternalLoginInfo Class 表15-10. ExternalLoginInfo类所定义的属性 Name 名称 Description 描述 DefaultUserName Returns the username 返回用户名 Email Returns the e-mail address 返回E-mail地址 ExternalIdentity Returns a ClaimsIdentity that identities the user 返回标识该用户的ClaimsIdentity Login Returns a UserLoginInfo that describes the external login 返回描述外部登录的UserLoginInfo I use the FindAsync method defined by the user manager class to locate the user based on the value of the ExternalLoginInfo.Login property, which returns an AppUser object if the user has been authenticated with the application before: 我使用了由用户管理器类所定义的FindAsync方法,以便根据ExternalLoginInfo.Login属性的值对用户进行定位,如果用户之前在应用程序中已经认证,该属性会返回一个AppUser对象: ...AppUser user = await UserManager.FindAsync(loginInfo.Login);... If the FindAsync method doesn’t return an AppUser object, then I know that this is the first time that this user has logged into the application, so I create a new AppUser object, populate it with values, and save it to the database. I also save details of how the user logged in so that I can find them next time: 如果FindAsync方法返回的不是AppUser对象,那么我便知道这是用户首次登录应用程序,于是便创建了一个新的AppUser对象,填充该对象的值,并将其保存到数据库。我还保存了用户如何登录的细节,以便下次能够找到他们: ...result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);... All that remains is to generate an identity the user, copy the claims provided by Google, and create an authentication cookie so that the application knows the user has been authenticated: 剩下的事情只是生成该用户的标识了,拷贝Google提供的声明(Claims),并创建一个认证Cookie,以使应用程序知道此用户已认证: ...ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie);ident.AddClaims(loginInfo.ExternalIdentity.Claims);AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);... 15.4.2 Testing Google Authentication 15.4.2 测试Google认证 There is one further change that I need to make before I can test Google authentication: I need to change the account verification I set up in Chapter 13 because it prevents accounts from being created with e-mail addresses that are not within the example.com domain. Listing 15-25 shows how I removed the verification from the AppUserManager class. 在测试Google认证之前还需要一处修改:需要修改第13章所建立的账号验证,因为它不允许example.com域之外的E-mail地址创建账号。清单15-25显示了如何在AppUserManager类中删除这种验证。 Listing 15-25. Disabling Account Validation in the AppUserManager.cs File 清单15-25. 在AppUserManager.cs文件中取消账号验证 using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.EntityFramework;using Microsoft.AspNet.Identity.Owin;using Microsoft.Owin;using Users.Models; namespace Users.Infrastructure {public class AppUserManager : UserManager<AppUser> {public AppUserManager(IUserStore<AppUser> store): base(store) {}public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options,IOwinContext context) {AppIdentityDbContext db = context.Get<AppIdentityDbContext>();AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); manager.PasswordValidator = new CustomPasswordValidator {RequiredLength = 6,RequireNonLetterOrDigit = false,RequireDigit = false,RequireLowercase = true,RequireUppercase = true}; //manager.UserValidator = new CustomUserValidator(manager) {// AllowOnlyAlphanumericUserNames = true,// RequireUniqueEmail = true//};return manager;} }} Tip you can use validation for externally authenticated accounts, but I am just going to disable the feature for simplicity. 提示:也可以使用外部已认证账号的验证,但这里出于简化,取消了这一特性。 To test authentication, start the application, click the Log In via Google button, and provide the credentials for a valid Google account. When you have completed the authentication process, your browser will be redirected back to the application. If you navigate to the /Claims/Index URL, you will be able to see how claims from the Google system have been added to the user’s identity, as shown in Figure 15-7. 为了测试认证,启动应用程序,通过点击“Log In via Google(通过Google登录)”按钮,并提供有效的Google账号凭据。当你完成了认证过程时,浏览器将被重定向回应用程序。如果导航到/Claims/Index URL,便能够看到来自Google系统的声明(Claims),已被添加到用户的标识中了,如图15-7所示。 Figure 15-7. Claims from Google 图15-7. 来自Google的声明(Claims) 15.5 Summary 15.5 小结 In this chapter, I showed you some of the advanced features that ASP.NET Identity supports. I demonstrated the use of custom user properties and how to use database migrations to preserve data when you upgrade the schema to support them. I explained how claims work and how they can be used to create more flexible ways of authorizing users. I finished the chapter by showing you how to authenticate users via Google, which builds on the ideas behind the use of claims. 本章向你演示了ASP.NET Identity所支持的一些高级特性。演示了自定义用户属性的使用,还演示了在升级数据架构时,如何使用数据库迁移保护数据。我解释了声明(Claims)的工作机制,以及如何将它们用于创建更灵活的用户授权方式。最后演示了如何通过Google进行认证结束了本章,这是建立在使用声明(Claims)的思想基础之上的。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gz19871113/article/details/108591802。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-28 08:49:21
283
转载
转载文章
...id") when matched then update set t1."text"=t2."text1" 为了避免T2中有多条数据对应T1中的数据,可以把sql改成如下的方式: MERGE INTO ZZ_TEST1 t1 USING ( SELECT FROM ZZ_TEST2 X WHERE X. ROWID = (SELECT MAX(Y.ROWID) FROM ZZ_TEST2 Y WHERE X."id" = Y."id" ) ) t2 ON (t1."id" = t2."pid") WHEN MATCHED THEN UPDATE SET t1."text" = t2."text1" 还有一种update from 的语法,经过测试在oracle和mysql中不适用 总结一下,项目中尝尝需要把一张表的字段更新到另一张表中的某一个字段。可以使用update语法,并要做好限定。会使用merge的语法,另外还有一种merge的语法也可以,update from 不能再oracle和mysql中使用。 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_42101720/article/details/116289534。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-10 10:14:44
798
转载
ElasticSearch
...字符串替换语法来指定查询参数,从而实现自定义的搜索请求。例如,我们可以在URL中加入某个字段值作为参数,然后通过URL模板将其替换为实际的值,从而得到我们想要的搜索结果。 二、如何在Kibana中设置URL模板? 在Kibana中设置URL模板非常简单,只需要按照以下步骤即可: 1. 在左侧菜单栏中选择要使用的索引,然后点击右上角的“高级选项”。 2. 在弹出的窗口中,点击“搜索模式”,然后选择“URL模板”。 3. 在打开的新窗口中,输入你要设置的URL模板。例如,你可以设置一个包含日期字段的模板,如下所示: /api/v1/app/kibana/management/dashboard/_data?index=_all&type=logs&page={page}&size={size}&sort=date desc&filter=%7B%22range%22%3A%7B%22date%22%3A%7B%22gte%22%3A%22{from_date}%22,%22lte%22%3A%22{to_date}%22%7D%7D%7D&query=%7B%22bool%22%3A%7B%22must%22%3A%5B%7B%22match_all%22%3A%7B%7D%7D%5D%7D 在这个模板中,“{from_date}”和“{to_date}”分别是日期范围的开始时间和结束时间。 4. 设置完模板后,点击“保存”。 现在,当你在Kibana中使用这个索引并开启搜索时,你可以看到一个新的按钮:“钻取”。点击这个按钮,就会打开一个新的搜索页面,并且会自动填充你刚才设置的URL模板。 三、如何使用URL模板进行搜索? 使用URL模板进行搜索也非常简单,只需要按照以下步骤即可: 1. 在左侧菜单栏中选择要使用的索引,然后点击右上角的“高级选项”。 2. 在弹出的窗口中,点击“搜索模式”,然后选择“URL模板”。 3. 在打开的新窗口中,输入你要搜索的关键词或其他条件,然后点击“搜索”按钮。 4. 如果你的搜索结果太多,可以使用上面设置的URL模板来进行进一步的过滤和排序。只需要在浏览器的地址栏中输入对应的URL,然后按回车键即可。 四、总结 总的来说,URL模板是Kibana提供的一种非常强大的工具,可以帮助我们在大量数据中快速找到我们需要的信息。你知道吗?如果我们巧妙地运用和设置URL模板,就能像魔法般让工作效率蹭蹭上涨,数据分析也会变得轻松又快乐,仿佛在玩乐中就把工作给干完了!希望这篇文章能对你有所帮助,如果你还有其他疑问,欢迎随时向我提问!
2023-08-09 23:59:55
494
雪域高原-t
ElasticSearch
...h提供的API来进行查询和检索操作。最后,我们可以通过前端界面展示查询结果。 下面,我们将通过一个具体的例子来演示如何使用Elasticsearch进行数据查询。 java // 创建一个新的索引 IndexRequest indexRequest = new IndexRequest("my_index"); indexRequest.source(jsonMapper.writeValueAsString(product), XContentType.JSON); client.index(indexRequest); // 查询索引中的数据 GetResponse response = client.get(new GetRequest("my_index", "product_id")); Map source = response.getSource(); 以上代码展示了如何向Elasticsearch中添加一条数据,并且查询索引中的数据。你瞧,Elasticsearch这玩意儿真心好用,压根没那么多复杂的步骤,就那么几个基础操作,轻轻松松就能搞定。 3. ListItem.Expandable ListItem.Expandable是Android Studio中的一种控件,它可以用来显示一个可以展开和收起的内容区域。用上这个小玩意儿,咱们就能轻轻松松展示大量信息,而且还不用担心占满屏幕空间的问题! 下面,我们将通过一个具体的例子来演示如何使用ListItem.Expandable。 xml android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"> android:id="@+id/myExpandableLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="FFFFFF" /> 以上代码展示了如何在ListView中使用MyExpandableLayout。通过这种方式,我们可以轻松地显示一个可以展开和收起的内容区域。 4. 总结 本文介绍了如何利用Elasticsearch的强大功能,以及如何使用ListItem.Expandable来显示一个可以扩展的列表。读完这篇文章,咱们就能掌握如何用Elasticsearch这个利器来对付海量数据,同时还能学到怎么运用ListItem.Expandable这个小窍门,让用户体验噌噌往上涨。 总的来说,Elasticsearch是一款非常强大的工具,它可以帮助我们高效地处理大量数据。而ListItem.Expandable则是一个非常实用的控件,它可以帮助我们优化用户体验。这两款产品都是非常值得推荐的。
2023-10-25 21:34:42
531
红尘漫步-t
MySQL
...,join类型是一种查询方式,它可以将两个或者更多的索引连接起来进行查询。这种查询方式在处理多表查询时非常有用,可以有效地提高查询效率。 例如,假设我们有两个索引,一个是用户索引,另一个是订单索引。如果你想找某个用户的订单详情,那就得使出“join”这个大招来查了。 三、join类型的实现 那么,如何在Elasticsearch中实现join类型呢?下面是一个简单的例子: 首先,我们需要创建两个索引,一个是用户索引,另一个是订单索引。 创建用户索引的脚本如下: bash PUT users/_doc/1 { "id": 1, "name": "张三", "email": "zhangsan@example.com" } PUT users/_doc/2 { "id": 2, "name": "李四", "email": "lisi@example.com" } 创建订单索引的脚本如下: bash PUT orders/_doc/1 { "id": 1, "user_id": 1, "product": "电视", "price": 3000 } PUT orders/_doc/2 { "id": 2, "user_id": 2, "product": "电脑", "price": 5000 } 然后,我们可以使用join类型来进行查询。查询语句如下: python GET /users/_search { "query": { "match_all": {} }, "size": 10, "from": 0, "sort": [ { "id": {"order": "asc"} } ], "aggs": { "orders": { "nested": { "path": "orders", "aggs": { "products": { "terms": { "field": "orders.product.keyword", "size": 10, "min_doc_count": 1 } } } } } } } 这个查询语句将会返回所有的用户信息,并且对于每一个用户,都会显示他购买的商品列表。这就是join类型的作用。 四、join类型的优缺点 join类型在处理多表查询时非常有用,可以有效地提高查询效率。但是,它也有一些缺点。首先,要是你有两个数据量都特别庞大的索引,那么执行join操作的时候,那速度可就慢得跟蜗牛赛跑似的。其次,join操作也会占用大量的内存资源。最后,假如这两个索引的数据结构对不上茬儿,那join操作就铁定没法顺利进行。 五、总结 总的来说,join类型是Elasticsearch中一种非常有用的查询方式,可以帮助我们处理多表查询。不过,咱们也得瞅瞅它的“短板”,根据实际情况灵活选择最合适的查询方法,可别让这个小家伙给局限住了~希望通过这篇接地气的文章,大家伙能真正掌握join类型这个知识点,然后在实际操作时,像玩转积木那样灵活运用起来。
2023-12-03 22:57:33
46
笑傲江湖_t
ElasticSearch
...的核心思想是在每一页查询结束时,记录下最后一条记录的排序字段值,并将这个值作为下一页查询的开始点,以此类推,直到达到我们需要的分页数量为止。 二、为什么需要使用 search_after 参数 使用传统的 from + size 方式进行分页,如果数据量很大,那么每一页都需要加载所有满足条件的记录到内存中,这样不仅消耗了大量的内存,而且会导致 CPU 资源的浪费。用 search_after 参数来实现分页的话,操作起来就像是这样:只需要轻轻拽住满足条件的最后一项记录,就能嗖地一下翻到下一页的结果。这样做,就像给内存和CPU减负瘦身一样,能大大降低它们的工作压力和损耗。 三、如何使用 search_after 参数 使用 search_after 参数非常简单,我们只需要在 Search API 中添加 search_after 参数即可。例如,如果我们有一个商品列表,我们想要获取第一页的商品列表,我们可以这样做: bash GET /products/_search { "from": 0, "size": 10, "sort": [ { "name": { "order": "asc" } } ], "search_after": [ { "name": "Apple" } ] } 在这个查询中,我们设置了 from 为 0,size 为 10,表示我们要获取第一页的商品列表,排序字段为 name,排序顺序为升序,最后,我们设置了 search_after 参数为 {"name": "Apple"},表示我们要从名为 Apple 的商品开始查找下一页的结果。 四、实战示例 为了更好地理解和掌握 search_after 参数的使用,我们来看一个实战示例。想象一下,我们运营着一个用户评论平台,现在呢,我们特别想瞅瞅用户们最新的那些精彩评论。不过,这里有个小插曲,就是这评论数量实在多得惊人,所以我们没法一股脑儿全捞出来看个遍哈。这时,我们就需要使用 search_after 参数来进行深度分页。 首先,我们需要创建一个 user_comment 文档类型,包含用户 id、评论内容和评论时间等字段。然后,我们可以编写如下的代码来获取最新的用户评论: python from datetime import datetime import requests 设置 Elasticsearch 的地址和端口 es_url = "http://localhost:9200" 创建 Elasticsearch 集群 es = Elasticsearch([es_url]) 获取最新的用户评论 def get_latest_user_comments(): 设置查询参数 params = { "index": "user_comment", "body": { "query": { "match_all": {} }, "sort": [ { "created_at": { "order": "desc" } } ], "size": 1, "search_after": [] } } 获取第一条记录 response = es.search(params) if not response["hits"]["hits"]: return [] 记录最后一条记录的排序字段值 last_record = response["hits"]["hits"][0] search_after = [last_record["_source"]["id"], last_record["_source"]["created_at"]] 获取下一条记录 while True: params["body"]["size"] += 1 params["body"]["search_after"] = search_after response = es.search(params) 如果没有更多记录,则返回所有记录 if not response["hits"]["hits"]: return [hit["_source"] for hit in response["hits"]["hits"]] else: last_record = response["hits"]["hits"][0] search_after = [last_record["_source"]["id"], last_record["_source"]["created_at"]] 在这段代码中,我们首先设置了一个空的 search_after 列表,然后执行了一次查询,获取了第一条记录,并将其存储在 last_record 变量中。接着,我们将 last_record 中的 id 和 created_at 字段的值添加到 search_after 列表中,再次执行查询,获取下一条记录。如此反复,直到获取到我们需要的所有记录为止。 五、总结 search_after 参数是 Elasticsearch 5.0 版本引入的一个新的分页方式,它可以让我们在每一页查询结束时,记录下最后一条记录的排序字段值,并将这个值作为下一页查询的开始点,以此类推广多获取我们需要的分页数量为止。这种方法不仅可以减少内存和 CPU 的消耗,而且还能够提高查询的效率,是一个非常值得使用的分页方式。
2023-03-26 18:17:46
576
人生如戏-t
ElasticSearch
...uery": { "match_all": {} } } 在这个例子中,我们发送了一个search操作请求,并指定了一个match_all查询。match_all查询表示匹配所有数据。所以,这条请求将会返回索引中的所有数据。 四、总结 通过上述步骤,我们可以很容易地将关系数据库中的数据导入到ElasticSearch中,并进行搜索。不过,这只是个入门级别的例子,真正实操起来,要考虑的因素可就多了去了,比如数据清洗这个环节,还有数据转换什么的,都是必不可少的步骤。所以,对那些琢磨着要把关系数据库里的数据挪到ElasticSearch的朋友们来说,这只是万里长征第一步。他们还需要投入更多的时间和精力,去深入学习、全面掌握ElasticSearch的各种知识和技术要点。
2023-06-25 20:52:37
456
梦幻星空-t
Kibana
... 3. 进行高级查询 除了基本的查询操作外,Kibana还提供了许多高级查询功能,如复杂查询、过滤器等。以下是一个使用复杂查询的例子: json GET my_index/_search { "query": { "bool": { "must": [ { "match": { "field1": "value1" } }, { "range": { "field2": { "gte": "value2" } } } ] } } } 四、使用Kibana的心得体会 作为一名长期使用Kibana的用户,我深感其强大之处。用Kibana这个工具,我就能像探照灯一样从海量数据里迅速捞出有价值的信息,然后把它们变成一目了然的可视化图表。这样一来,工作效率简直像是坐上了火箭,嗖嗖地往上窜! 同时,我也发现Kibana的一些不足之处。比如,它的学习过程就像个陡峭的山坡,你得花些时间去摸熟它各种功能的“脾气”。另外,虽然Kibana这家伙功能确实挺多样的,但它并不总是“万金油”,并不能适用于所有场合。有些时候,为了达到理想效果,咱们还得把它和其他工具小伙伴联手一起用才行。 总的来说,我认为Kibana是一款非常实用的实时数据处理工具,它可以帮助我们更好地管理和分析我们的数据,提高我们的工作效率。如果你也在寻找一款优秀的数据处理工具,那么不妨试试Kibana吧!
2023-12-18 21:14:25
302
山涧溪流-t
Mongo
.../ ...接下来进行查询和操作 }); 三、聚合框架基础 MongoDB的聚合框架(Aggregation Framework)是一个用于处理数据流的强大工具,它允许我们在服务器端进行复杂的计算和分析,而无需将所有数据传输回应用。基础的聚合操作包括$match、$project、$group等。例如,我们想找出某个集合中年龄大于30的用户数量: javascript db.users.aggregate([ { $match: { age: { $gt: 30 } } }, { $group: { _id: null, count: { $sum: 1 } } } ]).toArray(); 四、管道操作与复杂查询 聚合管道是一系列操作的序列,它们依次执行,形成了一个数据处理流水线。比如,我们可以结合$sort和$limit操作,获取年龄最大的前10位用户: javascript db.users.aggregate([ { $sort: { age: -1 } }, { $limit: 10 } ]).toArray(); 五、自定义聚合函数 MongoDB提供了很多预定义的聚合函数,如$avg、$min等。然而,如果你需要更复杂的计算,可以使用$function,定义一个JavaScript函数来执行自定义逻辑。例如,计算用户的平均购物金额: javascript db.orders.aggregate([ { $unwind: "$items" }, { $group: { _id: "$user_id", avgAmount: { $avg: "$items.price" } } } ]); 六、聚合管道优化 在处理大量数据时,优化聚合管道性能至关重要。你知道吗,有时候处理数据就像打游戏,我们可以用"$lookup"这个神奇的操作来实现内连,就像角色之间的无缝衔接。或者,如果你想给你的数据找个新家,别担心内存爆炸,用"$out"就能轻松把结果导向一个全新的数据仓库,超级方便!记得定期检查$explain()输出,了解每个阶段的性能瓶颈。 七、结论 MongoDB的聚合框架就像一把瑞士军刀,能处理各种数据处理需求。亲身体验和深度研习后,你就会发现这家伙的厉害之处,不只在于它那能屈能伸的灵巧,更在于它处理海量数据时的神速高效,简直让人惊叹!希望这些心得能帮助你在探索MongoDB的路上少走弯路,享受数据处理的乐趣。 记住,每一种技术都有其独特魅力,关键在于如何发掘并善用。加油,让我们一起在MongoDB的世界里探索更多可能!
2024-04-01 11:05:04
139
时光倒流
Kibana
...ibana的默认搜索查询:不准确或不包含所需数据的深度解析与优化策略 1. 引言 大家好,当你在使用Kibana进行数据分析时,是否曾遇到过这样的困扰:明明Elasticsearch中存储了大量宝贵的数据,但在Kibana中执行搜索查询时,返回的结果却并不尽如人意——它们可能不够全面,甚至漏掉了你真正需要的关键信息。这就是我们今天要探讨的主题:“Kibana的默认搜索查询不准确或不包含所需数据”。来吧,咱们一起钻得深一点,把这个问题摸个透彻。我打算通过实实在在的例子,手把手教你如何巧妙地优化查询,从而捞到更精准、更全面的信息。 2. Kibana搜索查询基础原理 首先,我们需要理解Kibana搜索背后的机制。Kibana是基于Elasticsearch的可视化平台,默认的搜索查询其实采用了Elasticsearch的“match”查询,它会对索引中的所有字段进行全文本搜索。不过呢,这种模糊匹配的方法,在某些特定情况下可能不太灵光。比如说,当我们面对结构严谨的数据,或者需要找的东西必须严丝合缝地匹配时,搜出来的结果就可能不尽人意了。 3. 默认搜索查询的问题案例 (以下代码示例假设我们有一个名为"logstash-"的索引,其中包含日志数据) json GET logstash-/_search { "query": { "match": { "message": "error" } } } 上述代码表示在"logstash-"的所有文档中查找含有"error"关键词的消息。但是,你知道吗,就算消息内容显示是“application has no error”,这个记录也会被挖出来,这明显不是我们想要的结果啊。 4. 优化搜索查询的方法 (1)精准匹配查询 为了精确匹配某个字段的内容,我们可以采用term查询而非match查询。 json GET logstash-/_search { "query": { "term": { "status.keyword": "error" } } } 在这个例子中,我们针对"status"字段进行精确匹配,".keyword"后缀确保了我们是在对已分析过的非文本字段进行查询。 (2)范围查询和多条件查询 如果你需要根据时间范围或者多个条件筛选数据,可以使用range和bool复合查询。 json GET logstash-/_search { "query": { "bool": { "must": [ { "term": { "status.keyword": "error" } }, { "range": { "@timestamp": { "gte": "now-1d", "lte": "now" } } } ] } } } 此处的例子展示了同时满足状态为"error"且在过去24小时内的日志记录。 5. 总结与思考 Kibana的默认搜索查询方式虽便捷,但其灵活性和准确性在面对复杂需求时可能会有所欠缺。熟悉并灵活运用Elasticsearch的各种查询“独门语言”(DSL,也就是领域特定语言),就像掌握了一套搜索大法,能够让你随心所欲地定制查询条件,这样一来,搜出来的结果不仅更贴切你想要的,而且信息更全面、准确度蹭蹭上涨,就像是给搜索功能插上了小翅膀一样。这就像是拥有一把精巧的钥匙,能够打开Elasticsearch这座数据宝库中每一扇隐藏的门。 所以,下次当你在Kibana中发现搜索结果不尽如人意时,请不要急于怀疑数据的质量,而是尝试调整你的查询策略,让数据告诉你它的故事。记住了啊,每一次咱们对查询方法的改良和优化,其实就像是在数据的世界里不断挖掘宝藏,步步深入,逐渐揭开它的神秘面纱。这不仅是我们对数据理解越来越透彻的过程,更是咱们提升数据分析功力、练就火眼金睛的关键步骤!
2023-05-29 19:00:46
487
风轻云淡
Spark
...t = { key match { case _: Int => (key.toInt % numPartitions) // 假设key是个整数,取余操作确保均匀分布 case _ => throw new IllegalArgumentException(s"Key must be an integer for CustomPartitioner") } } override def isGlobalPartition(index: Int): Boolean = false } val customData = Array((1, "value1"), (2, "value2"), (3, "value3"), (4, "value4")) val customRdd = spark.sparkContext.parallelize(customData).partitionBy(3, new CustomPartitioner) 四、应用与优化 自定义Partitioner的应用场景非常广泛。比如,当我们做关联查询这事儿的时候,就像两个大表格要相互配对找信息一样,如果找到这两表格在某一列上有紧密的联系,那咱们就可以利用这个“共同点”来定制分区方案。这样一来,关联查询就像分成了很多小任务,在特定的机器上并行处理,大大加快了配对的速度,提升整体性能。 此外,还可以根据业务需求动态调整分区数量。当数据量蹭蹭往上涨的时候,咱们可以灵活调整Partitioner这个家伙的numPartitions属性,让它帮忙重新分配一下数据,确保所有任务都能“雨露均沾”,避免出现谁干得多、谁干得少的情况,保持大家的工作量均衡。 五、结论 总之,理解和掌握Spark中的Partitioner设计模式是高效利用Spark的重要环节。自定义Partitioner这个功能,那可是超级灵活的家伙,它让我们能够根据实际场景的需要,亲手安排数据分布,确保每个数据都落脚到最合适的位置。这样一来,不仅能让处理速度嗖嗖提升,还能让任务表现得更加出色,就像给机器装上了智能导航,让数据处理的旅程更加高效顺畅。希望通过这篇接地气的文章,您能像老司机一样熟练掌握Spark的Partitioner功能,从而更上一层楼,把Spark在大数据处理领域的威力发挥得淋漓尽致。
2024-02-26 11:01:20
71
春暖花开-t
Kibana
...icsearch发出查询请求,然后把那些符合你条件的数据给挖出来,以一种可视化的方式展示给你看,就像变魔术一样。如果这个过程耗时较长或者返回为空,通常涉及到以下几个可能因素: - 查询语句过于复杂或宽泛 - Elasticsearch集群性能瓶颈 - 网络延迟或带宽限制 - Kibana自身的配置问题 3. 深入排查原因(举例说明) 示例1:查询语句分析 json GET /my_index/_search { "query": { "match_all": {} }, "size": 5000 } 上述代码是一个简单的match_all查询,试图从my_index中获取5000条记录。如果您的索引数据量巨大,这样的查询将会消耗大量资源,导致Discover页面加载缓慢。此时,可以尝试优化查询条件,比如添加时间范围过滤、字段筛选等。 示例2:检查Elasticsearch性能指标 借助Elasticsearch的监控API,我们可以获取节点、索引及查询的性能指标: bash curl -X GET 'localhost:9200/_nodes/stats/indices,query_cache?human&pretty' 通过观察查询缓存命中率、分片分配状态以及CPU、内存使用情况,可以帮助我们判断是否因ES集群性能瓶颈导致Discover加载慢。 4. 解决策略与实践 策略1:优化查询条件与DSL 确保在Discover页面使用的查询语句高效且有针对性。例如,使用range查询限定时间范围,使用term或match精确匹配特定字段,或利用bool查询进行复杂的组合条件过滤。 策略2:调整Elasticsearch集群配置 - 增加硬件资源,如提升CPU核数、增加内存大小。 - 调整索引设置,如合理设置分片数量和副本数量,优化refresh interval以平衡写入性能与实时性需求。 - 启用并适当调整查询缓存大小。 策略3:优化Kibana配置 在Kibana.yml配置文件中,可以对discover页面的默认查询参数进行调整,如设置默认时间范围、最大返回文档数等,以降低一次性加载数据量。 5. 结论与探讨 解决Kibana Discover页面加载数据慢或空白的问题,需要结合实际情况,从查询语句优化、Elasticsearch集群调优以及Kibana自身配置多方面着手。在实际操作的过程中,我们得像个福尔摩斯那样,一探究竟,把问题的根源挖个底朝天。然后,咱们得冷静分析,理性思考,不断尝试各种可能的优化方案,这样才能够让咱们的数据分析之路走得更加顺风顺水,畅通无阻。记住,每一次的成功优化都是对我们技术理解与应用能力的一次锤炼和提升!
2023-08-21 15:24:10
298
醉卧沙场
Logstash
... { date { match => ["timestamp", "ISO8601"] } } output { elasticsearch { hosts => ["localhost:9200"] index => "app-%{+YYYY.MM.dd}" } } 在这个例子中,如果Logstash服务器的时间比Elasticsearch服务器滞后了几个小时,那么根据Logstash处理的日志时间生成的索引名(例如app-2023.04.07)可能已经存在于Elasticsearch中,从而产生索引冲突。 3. 解决方案 保持系统时间同步 NTP服务 确保所有涉及的服务器均使用网络时间协议(Network Time Protocol, NTP)与权威时间源进行同步。在Linux系统中,可以通过以下命令安装并配置NTP服务: bash sudo apt-get install ntp sudo ntpdate pool.ntp.org 定期检查与纠正 对于关键业务系统,建议设置定时任务定期检查各节点时间偏差,并在必要时强制同步。此外,可以考虑在应用程序层面增加对时间差异的容忍度和容错机制。 容器环境 在Docker或Kubernetes环境中运行Logstash时,应确保容器内的时间与宿主机或集群其他组件保持同步。要让容器和宿主机的时间保持同步,一个实用的方法就是把宿主机里的那个叫/etc/localtime的文件“搬”到容器内部,这样就能实现时间共享啦,就像你和朋友共用一块手表看时间一样。 4. 总结与思考 面对Logstash与相关组件间系统时间不同步带来的挑战,我们需要充分认识到时间同步的重要性,并采取有效措施加以预防和修正。在日常运维这个活儿里,咱得把它纳入常规的“体检套餐”里,确保整个数据流处理这条生产线从头到尾都坚挺又顺畅,一步一个脚印,不出一丝差错。同时呢,随着技术的日益进步和实践经验日渐丰富,我们也要积极开动脑筋,探寻更高阶的时间同步策略,还有故障应急处理方案。这样一来,才能更好地应对那些复杂多变、充满挑战的生产环境需求嘛。
2023-11-18 11:07:16
305
草原牧歌
ElasticSearch
...更轻松地找到与我们的查询相匹配的结果。 在Elasticsearch中,我们可以使用fuzziness选项启用Fuzzy搜索。下面是一个使用Fuzzy搜索的例子: php-template GET /my_index/_search { "query": { "multi_match": { "query": "some text", "fields": ["text"], "fuzziness": "auto" } } } 在这个例子中,我们正在搜索名为“my_index”的索引中的所有包含“some text”的文档。"Fuzziness"这个参数你要是设成“auto”,那就相当于告诉Elasticsearch:伙计,你看着办吧,根据查询字符串的长短自己挑个最合适的模糊匹配程度哈! 2. 近义词搜索 近义词搜索是指在一个查询中替换一个单词为其同义词的能力。这对于处理同义词丰富且变化多端的数据集非常有用。 在Elasticsearch中,我们可以使用synonyms选项启用近义词搜索。下面是一个使用近义词搜索的例子: json PUT /my_index/_settings { "analysis": { "analyzer": { "my_analyzer": { "tokenizer": "standard", "filter": [ { "type": "synonym", "synonyms_path": "/path/to/synonyms.txt" } ] } } } } POST /my_index/_doc { "text": "This is an example sentence." } 在这个例子中,我们首先创建了一个名为“my_analyzer”的分析器,该分析器使用标准分词器和一个加载了同义词的过滤器。然后,我们使用这个分析器来索引一条包含“example”单词的文档。当你在搜索时用上了“sample”这个同义词,Elasticsearch会超级给力地找出和你最初输入的那个查询一模一样的结果来。就像是有个贴心的小助手,无论你怎么变着花样描述,它都能准确理解你的意思,并且给你找出完全匹配的答案。 3. 值匹配搜索 值匹配搜索是指在查询中指定要匹配的具体值的能力。这对于处理类型明确的数据非常有用,例如日期、数字或地理位置等。 在Elasticsearch中,我们可以使用value_match选项启用值匹配搜索。下面是一个使用值匹配搜索的例子: json GET /my_index/_search { "query": { "bool": { "must": [ { "range": { "date_field": { "gte": "now-3d" } } }, { "match": { "string_field": "some text" } } ] } } } 在这个例子中,我们正在搜索名为“my_index”的索引中所有满足两个条件的文档:文档的“date字段”必须大于等于当前日期减去3天,并且文档的“string字段”必须包含“some text”。 四、总结 Elasticsearch不仅提供了基本的搜索功能,而且还提供了许多高级搜索功能。通过利用这些功能,我们可以更高效地搜索和管理我们的数据。 在未来的文章中,我们将继续探索更多的Elasticsearch功能,并提供更多的代码示例。感谢您的阅读,如果您有任何疑问或反馈,请随时告诉我。
2023-02-26 23:53:35
527
岁月如歌-t
MyBatis
...搜索可以处理更复杂的查询条件,比如忽略大小写、支持布尔逻辑运算等。在数据库层面,这通常涉及到使用特定的全文索引和查询语法。 假设你正在开发一个电商平台,用户需要能够通过输入关键词快速找到他们想要的商品信息。要是咱们数据库里存了好多商品描述,那单靠简单的LIKE查询可能就搞不定事儿了,速度会特别慢。这时候,引入全文搜索就显得尤为重要。 2. MyBatis中实现全文搜索的基本思路 在MyBatis中实现全文搜索并不是直接由框架提供的功能,而是需要结合数据库本身的全文索引功能来实现。不同的数据库在全文搜索这块各有各的招数。比如说,MySQL里的InnoDB引擎就支持全文索引,而PostgreSQL更是自带强大的全文搜索功能,用起来特别方便。这里我们以MySQL为例进行讲解。 2.1 数据库配置 首先,你需要确保你的数据库支持全文索引,并且已经为相关字段启用了全文索引。比如,在MySQL中,你可以这样创建一个带有全文索引的表: sql CREATE TABLE product ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), description TEXT, FULLTEXT(description) ); 这里,我们为description字段添加了一个全文索引,这意味着我们可以在这个字段上执行全文搜索。 2.2 MyBatis映射文件配置 接下来,在MyBatis的映射文件(Mapper XML)中定义相应的SQL查询语句。这里的关键在于正确地构建全文搜索的SQL语句。比如,假设我们要实现根据商品描述搜索商品的功能,可以这样编写: xml SELECT FROM product WHERE MATCH(description) AGAINST ({keyword} IN NATURAL LANGUAGE MODE) 这里的MATCH(description) AGAINST ({keyword})就是全文搜索的核心部分。“IN NATURAL LANGUAGE MODE”就是用大白话来搜东西,这种方式更直接、更接地气。搜出来的结果也会按照跟你要找的东西的相关程度来排个序。 3. 实际应用中的常见问题及解决方案 在实际开发过程中,可能会遇到一些配置不当导致全文搜索功能失效的情况。这里,我将分享几个常见的问题及其解决方案。 3.1 搜索结果不符合预期 问题描述:当你执行全文搜索时,发现搜索结果并不是你期望的那样,可能是因为搜索关键词太短或者太常见,导致匹配度不高。 解决方法:尝试调整全文搜索的模式,比如使用BOOLEAN MODE来提高搜索精度。此外,确保搜索关键词足够长且具有一定的独特性,可以显著提高搜索效果。 xml SELECT FROM product WHERE MATCH(description) AGAINST ({keyword} IN BOOLEAN MODE) 3.2 性能瓶颈 问题描述:随着数据量的增加,全文搜索可能会变得非常慢,影响用户体验。 解决方法:优化索引设计,比如适当减少索引字段的数量,或者对索引进行分区。另外,也可以考虑在应用层缓存搜索结果,减少数据库负担。 4. 总结与展望 通过上述内容,我们了解了如何在MyBatis项目中正确配置全文搜索功能,并探讨了一些实际操作中可能遇到的问题及解决策略。全文搜索这东西挺强大的,但你得小心翼翼地设置才行。要是设置得好,不仅能让人用起来更爽,还能让整个应用变得更全能、更灵活。 当然,这只是全文搜索配置的一个起点。随着业务越做越大,技术也越来越先进,我们可以试试更多高大上的功能,比如支持多种语言,还能处理同义词啥的。希望本文能对你有所帮助,如果有任何疑问或想法,欢迎随时交流讨论! --- 希望这篇文章能够帮助到你,如果有任何具体的需求或者想了解更多细节,随时告诉我!
2024-11-06 15:45:32
135
岁月如歌
ElasticSearch
... { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } } date { match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ] } } output { elasticsearch { hosts => ["localhost:9200"] index => "nginx-access-%{+YYYY.MM.dd}" } } 这段配置文件告诉Logstash从/var/log/nginx/access.log文件读取数据,使用Grok过滤器解析日志格式,然后将解析后的数据存入Elasticsearch中。这里的hosts参数指定了Elasticsearch的地址,index参数定义了索引的命名规则。 5. 实战演练 分析数据 最后,让我们来看看如何通过Elasticsearch查询和分析这些数据。好了,假设你已经把日志数据成功导入到了Elasticsearch里,现在你想看看最近一天内哪些网址被访问得最多。 bash GET /nginx-access-/_search { "size": 0, "aggs": { "top_pages": { "terms": { "field": "request", "size": 10 } } } } 这段查询语句会返回过去一天内访问量最高的10个URL。通过这种方式,你可以快速获取关键信息,从而做出相应的决策。 6. 总结与展望 通过这篇文章,我们学习了如何使用Elasticsearch异步采集非业务数据,并进行了简单的分析。这个过程让我们更懂用户的套路,还挖出了不少宝贝,帮我们更好地升级产品和服务。 当然,实际操作中可能会遇到各种问题和挑战,但只要保持耐心,不断实践和探索,相信你一定能够掌握这项技能。希望这篇教程能对你有所帮助,如果你有任何疑问或者建议,欢迎随时留言交流! --- 好了,朋友们,今天的分享就到这里。希望你能从中获得灵感,开始你的Elasticsearch之旅。记住,技术的力量在于应用,让我们一起用它来创造更美好的世界吧!
2024-12-29 16:00:49
75
飞鸟与鱼_
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
tail -n 10 file.txt
- 查看文件后10行。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"